From 05d48b936f3733ff1d64de91a47465682603b133 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Fri, 15 Mar 2024 03:21:55 +0100 Subject: [PATCH 1/6] Rename AstConv to HIR ty lowering This includes updating astconv-related items and a few local variables. --- .../rustc_hir_analysis/src/astconv/bounds.rs | 28 +- .../rustc_hir_analysis/src/astconv/errors.rs | 20 +- .../src/astconv/generics.rs | 10 +- .../rustc_hir_analysis/src/astconv/lint.rs | 4 +- .../rustc_hir_analysis/src/astconv/mod.rs | 312 +++++++++--------- .../src/astconv/object_safety.rs | 18 +- .../rustc_hir_analysis/src/check/wfcheck.rs | 2 +- compiler/rustc_hir_analysis/src/collect.rs | 65 ++-- .../src/collect/item_bounds.rs | 10 +- .../src/collect/predicates_of.rs | 34 +- .../src/collect/resolve_bound_vars.rs | 6 +- .../rustc_hir_analysis/src/collect/type_of.rs | 24 +- .../rustc_hir_analysis/src/hir_wf_check.rs | 2 +- compiler/rustc_hir_analysis/src/lib.rs | 4 +- compiler/rustc_hir_typeck/src/closure.rs | 18 +- compiler/rustc_hir_typeck/src/coercion.rs | 2 +- compiler/rustc_hir_typeck/src/expr.rs | 10 +- .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 74 ++--- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 12 +- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 12 +- .../src/fn_ctxt/suggestions.rs | 10 +- .../rustc_hir_typeck/src/gather_locals.rs | 2 +- compiler/rustc_hir_typeck/src/lib.rs | 4 +- .../rustc_hir_typeck/src/method/confirm.rs | 22 +- .../rustc_trait_selection/src/traits/mod.rs | 2 +- .../src/traits/object_safety.rs | 2 +- src/librustdoc/clean/mod.rs | 30 +- .../clippy_lints/src/implicit_hasher.rs | 4 +- .../src/implied_bounds_in_impls.rs | 4 +- .../src/types/redundant_allocation.rs | 4 +- .../clippy/clippy_lints/src/types/vec_box.rs | 6 +- .../src/unconditional_recursion.rs | 4 +- .../src/uninhabited_references.rs | 4 +- src/tools/clippy/clippy_lints/src/use_self.rs | 4 +- .../clippy_lints/src/zero_sized_map_values.rs | 4 +- 35 files changed, 371 insertions(+), 402 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/astconv/bounds.rs b/compiler/rustc_hir_analysis/src/astconv/bounds.rs index 7a5cb6e9d6f90..dd11f58ca1982 100644 --- a/compiler/rustc_hir_analysis/src/astconv/bounds.rs +++ b/compiler/rustc_hir_analysis/src/astconv/bounds.rs @@ -12,13 +12,13 @@ use rustc_trait_selection::traits; use rustc_type_ir::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}; use smallvec::SmallVec; -use crate::astconv::{AstConv, OnlySelfBounds, PredicateFilter}; +use crate::astconv::{HirTyLowerer, OnlySelfBounds, PredicateFilter}; use crate::bounds::Bounds; use crate::errors; -impl<'tcx> dyn AstConv<'tcx> + '_ { +impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// Sets `implicitly_sized` to true on `Bounds` if necessary - pub(crate) fn add_implicitly_sized( + pub(crate) fn add_sized_bound( &self, bounds: &mut Bounds<'tcx>, self_ty: Ty<'tcx>, @@ -117,7 +117,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref` /// for more details. #[instrument(level = "debug", skip(self, ast_bounds, bounds))] - pub(crate) fn add_bounds<'hir, I: Iterator>>( + pub(crate) fn lower_poly_bounds<'hir, I: Iterator>>( &self, param_ty: Ty<'tcx>, ast_bounds: I, @@ -145,7 +145,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } hir::TraitBoundModifier::Maybe => continue, }; - let _ = self.instantiate_poly_trait_ref( + let _ = self.lower_poly_trait_ref( &poly_trait_ref.trait_ref, poly_trait_ref.span, constness, @@ -156,7 +156,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { ); } hir::GenericBound::Outlives(lifetime) => { - let region = self.ast_region_to_region(lifetime, None); + let region = self.lower_lifetime(lifetime, None); bounds.push_region_bound( self.tcx(), ty::Binder::bind_with_vars( @@ -186,7 +186,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`. /// /// `span` should be the declaration size of the parameter. - pub(crate) fn compute_bounds( + pub(crate) fn lower_mono_bounds( &self, param_ty: Ty<'tcx>, ast_bounds: &[hir::GenericBound<'tcx>], @@ -201,7 +201,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { PredicateFilter::SelfOnly | PredicateFilter::SelfThatDefines(_) => OnlySelfBounds(true), }; - self.add_bounds( + self.lower_poly_bounds( param_ty, ast_bounds.iter().filter(|bound| match filter { PredicateFilter::All @@ -234,7 +234,7 @@ 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, dup_bindings, path_span))] - pub(super) fn add_predicates_for_ast_type_binding( + pub(super) fn lower_assoc_item_binding( &self, hir_ref_id: hir::HirId, trait_ref: ty::PolyTraitRef<'tcx>, @@ -272,7 +272,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { ty::AssocKind::Type }; - let candidate = if self.trait_defines_associated_item_named( + let candidate = if self.probe_trait_that_defines_assoc_item( trait_ref.def_id(), assoc_kind, binding.ident, @@ -282,7 +282,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } else { // Otherwise, we have to walk through the supertraits to find // one that does define it. - self.one_bound_for_assoc_item( + self.probe_single_bound_for_assoc_item( || traits::supertraits(tcx, trait_ref), trait_ref.skip_binder().print_only_trait_name(), None, @@ -417,7 +417,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { infer_args: false, }; - let alias_args = self.create_args_for_associated_item( + let alias_args = self.lower_generic_args_of_assoc_item( path_span, assoc_item.def_id, &item_segment, @@ -451,7 +451,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } hir::TypeBindingKind::Equality { term } => { let term = match term { - hir::Term::Ty(ty) => self.ast_ty_to_ty(ty).into(), + hir::Term::Ty(ty) => self.lower_ty(ty).into(), hir::Term::Const(ct) => ty::Const::from_anon_const(tcx, ct.def_id).into(), }; @@ -514,7 +514,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // for the `Self` type. if !only_self_bounds.0 { let param_ty = Ty::new_alias(tcx, ty::Projection, projection_ty.skip_binder()); - self.add_bounds( + self.lower_poly_bounds( param_ty, ast_bounds.iter(), bounds, diff --git a/compiler/rustc_hir_analysis/src/astconv/errors.rs b/compiler/rustc_hir_analysis/src/astconv/errors.rs index 68896768e8d8a..bae427a8c84a8 100644 --- a/compiler/rustc_hir_analysis/src/astconv/errors.rs +++ b/compiler/rustc_hir_analysis/src/astconv/errors.rs @@ -1,4 +1,4 @@ -use crate::astconv::AstConv; +use crate::astconv::HirTyLowerer; use crate::errors::{ self, AssocTypeBindingNotAllowed, ManualImplementation, MissingTypeParams, ParenthesizedFnTraitExpansion, @@ -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<'tcx> dyn AstConv<'tcx> + '_ { +impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// 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( @@ -311,7 +311,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // FIXME(associated_const_equality): This has quite a few false positives and negatives. let wrap_in_braces_sugg = if let Some(binding) = binding && let hir::TypeBindingKind::Equality { term: hir::Term::Ty(hir_ty) } = binding.kind - && let ty = self.ast_ty_to_ty(hir_ty) + && let ty = self.lower_ty(hir_ty) && (ty.is_enum() || ty.references_error()) && tcx.features().associated_const_equality { @@ -349,7 +349,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { }) } - pub(super) fn report_ambiguous_associated_type( + pub(super) fn report_ambiguous_assoc_ty( &self, span: Span, types: &[String], @@ -458,7 +458,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { reported } - pub(crate) fn complain_about_ambiguous_inherent_assoc_type( + pub(crate) fn complain_about_ambiguous_inherent_assoc_ty( &self, name: Ident, candidates: Vec, @@ -471,14 +471,14 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { "multiple applicable items in scope" ); err.span_label(name.span, format!("multiple `{name}` found")); - self.note_ambiguous_inherent_assoc_type(&mut err, candidates, span); + self.note_ambiguous_inherent_assoc_ty(&mut err, candidates, span); let reported = err.emit(); self.set_tainted_by_errors(reported); reported } // FIXME(fmease): Heavily adapted from `rustc_hir_typeck::method::suggest`. Deduplicate. - fn note_ambiguous_inherent_assoc_type( + fn note_ambiguous_inherent_assoc_ty( &self, err: &mut Diag<'_>, candidates: Vec, @@ -521,7 +521,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } // FIXME(inherent_associated_types): Find similarly named associated types and suggest them. - pub(crate) fn complain_about_inherent_assoc_type_not_found( + pub(crate) fn complain_about_inherent_assoc_ty_not_found( &self, name: Ident, self_ty: Ty<'tcx>, @@ -697,7 +697,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { /// reasonable suggestion on how to write it. For the case of multiple associated types in the /// same trait bound have the same name (as they come from different supertraits), we instead /// emit a generic note suggesting using a `where` clause to constraint instead. - pub(crate) fn complain_about_missing_associated_types( + pub(crate) fn complain_about_missing_assoc_tys( &self, associated_types: FxIndexMap>, potential_assoc_types: Vec, @@ -1027,7 +1027,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } /// Emits an error regarding forbidden type binding associations -pub fn prohibit_assoc_ty_binding( +pub fn prohibit_assoc_item_binding( tcx: TyCtxt<'_>, span: Span, segment: Option<(&hir::PathSegment<'_>, Span)>, diff --git a/compiler/rustc_hir_analysis/src/astconv/generics.rs b/compiler/rustc_hir_analysis/src/astconv/generics.rs index 42e303c10ea84..9ad6fec22ac69 100644 --- a/compiler/rustc_hir_analysis/src/astconv/generics.rs +++ b/compiler/rustc_hir_analysis/src/astconv/generics.rs @@ -1,7 +1,7 @@ use super::IsMethodCall; use crate::astconv::{ - errors::prohibit_assoc_ty_binding, CreateInstantiationsForGenericArgsCtxt, ExplicitLateBound, - GenericArgCountMismatch, GenericArgCountResult, GenericArgPosition, + errors::prohibit_assoc_item_binding, ExplicitLateBound, GenericArgCountMismatch, + GenericArgCountResult, GenericArgPosition, GenericArgsLowerer, }; use crate::structured_errors::{GenericArgsInfo, StructuredDiag, WrongNumberOfGenericArgs}; use rustc_ast::ast::ParamKindOrd; @@ -172,14 +172,14 @@ fn generic_arg_mismatch_err( /// instantiate a `GenericArg`. /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then /// creates a suitable inference variable. -pub fn create_args_for_parent_generic_args<'tcx: 'a, 'a>( +pub fn lower_generic_args<'tcx: 'a, 'a>( tcx: TyCtxt<'tcx>, def_id: DefId, parent_args: &[ty::GenericArg<'tcx>], has_self: bool, self_ty: Option>, arg_count: &GenericArgCountResult, - ctx: &mut impl CreateInstantiationsForGenericArgsCtxt<'a, 'tcx>, + ctx: &mut impl GenericArgsLowerer<'a, 'tcx>, ) -> GenericArgsRef<'tcx> { // Collect the segments of the path; we need to instantiate arguments // for parameters throughout the entire path (wherever there are @@ -456,7 +456,7 @@ pub(crate) fn check_generic_arg_count( if gen_pos != GenericArgPosition::Type && let Some(b) = gen_args.bindings.first() { - prohibit_assoc_ty_binding(tcx, b.span, None); + prohibit_assoc_item_binding(tcx, b.span, None); } let explicit_late_bound = diff --git a/compiler/rustc_hir_analysis/src/astconv/lint.rs b/compiler/rustc_hir_analysis/src/astconv/lint.rs index b421a33ba294b..80be563686a71 100644 --- a/compiler/rustc_hir_analysis/src/astconv/lint.rs +++ b/compiler/rustc_hir_analysis/src/astconv/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<'tcx> dyn AstConv<'tcx> + '_ { +impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// 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/astconv/mod.rs index a912d7f578dd0..14864da1e39cd 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -8,8 +8,8 @@ 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::astconv::errors::prohibit_assoc_item_binding; +use crate::astconv::generics::{check_generic_arg_count, lower_generic_args}; use crate::bounds::Bounds; use crate::collect::HirPlaceholderCollector; use crate::errors::AmbiguousLifetimeBound; @@ -44,7 +44,7 @@ use std::fmt::Display; use std::slice; #[derive(Debug)] -pub struct PathSeg(pub DefId, pub usize); +pub struct GenericPathSegment(pub DefId, pub usize); #[derive(Copy, Clone, Debug)] pub struct OnlySelfBounds(pub bool); @@ -67,7 +67,7 @@ pub enum PredicateFilter { SelfAndAssociatedTypeBounds, } -pub trait AstConv<'tcx> { +pub trait HirTyLowerer<'tcx> { fn tcx(&self) -> TyCtxt<'tcx>; fn item_def_id(&self) -> DefId; @@ -84,7 +84,7 @@ pub trait AstConv<'tcx> { /// but this can lead to cycle errors. The problem is that we have /// to do this resolution *in order to create the predicates in /// the first place*. Hence, we have this "special pass". - fn get_type_parameter_bounds( + fn probe_ty_param_bounds( &self, span: Span, def_id: LocalDefId, @@ -99,7 +99,7 @@ pub trait AstConv<'tcx> { fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>; /// Returns `true` if `_` is allowed in type signatures in the current context. - fn allow_ty_infer(&self) -> bool; + fn allow_infer(&self) -> bool; /// Returns the const to use when a const is omitted. fn ct_infer( @@ -116,7 +116,7 @@ pub trait AstConv<'tcx> { /// signatures for that reason. In a function body, we can always /// handle it because we can use inference variables to remove the /// late-bound regions. - fn projected_ty_from_poly_trait_ref( + fn lower_assoc_ty( &self, span: Span, item_def_id: DefId, @@ -139,7 +139,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, { @@ -197,7 +197,7 @@ pub struct GenericArgCountResult { pub correct: Result<(), GenericArgCountMismatch>, } -pub trait CreateInstantiationsForGenericArgsCtxt<'a, 'tcx> { +pub trait GenericArgsLowerer<'a, 'tcx> { fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool); fn provided_kind( @@ -214,9 +214,9 @@ pub trait CreateInstantiationsForGenericArgsCtxt<'a, 'tcx> { ) -> ty::GenericArg<'tcx>; } -impl<'tcx> dyn AstConv<'tcx> + '_ { +impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { #[instrument(level = "debug", skip(self), ret)] - pub fn ast_region_to_region( + pub fn lower_lifetime( &self, lifetime: &hir::Lifetime, def: Option<&ty::GenericParamDef>, @@ -273,13 +273,13 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { /// 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_generic_args_of_path_segment( &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_generic_args_of_path( span, def_id, &[], @@ -288,9 +288,8 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { ty::BoundConstness::NotConst, ); if let Some(b) = item_segment.args().bindings.first() { - prohibit_assoc_ty_binding(self.tcx(), b.span, Some((item_segment, span))); + prohibit_assoc_item_binding(self.tcx(), b.span, Some((item_segment, span))); } - args } @@ -328,7 +327,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { /// 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( + fn lower_generic_args_of_path( &self, span: Span, def_id: DefId, @@ -381,8 +380,8 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { return (tcx.mk_args(parent_args), arg_count); } - struct InstantiationsForAstPathCtxt<'a, 'tcx> { - astconv: &'a dyn AstConv<'tcx>, + struct GenericArgsCtxt<'a, 'tcx> { + lowerer: &'a dyn HirTyLowerer<'tcx>, def_id: DefId, generic_args: &'a GenericArgs<'tcx>, span: Span, @@ -390,9 +389,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { infer_args: bool, } - impl<'a, 'tcx> CreateInstantiationsForGenericArgsCtxt<'a, 'tcx> - for InstantiationsForAstPathCtxt<'a, 'tcx> - { + impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsCtxt<'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) @@ -407,7 +404,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { 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 { @@ -426,17 +423,17 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { }, ); } - if let (hir::TyKind::Infer, false) = (&ty.kind, self.astconv.allow_ty_infer()) { + if let (hir::TyKind::Infer, false) = (&ty.kind, self.lowerer.allow_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_lifetime(lt, Some(param)).into() } (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => { handle_ty_args(has_default, ty) @@ -455,8 +452,8 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { .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_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() @@ -475,10 +472,10 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { 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"); @@ -504,7 +501,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } 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() @@ -526,7 +523,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { .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() @@ -537,8 +534,8 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } } - let mut args_ctx = InstantiationsForAstPathCtxt { - astconv: self, + let mut args_ctx = GenericArgsCtxt { + lowerer: self, def_id, span, generic_args: segment.args(), @@ -557,7 +554,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { arg_count.correct = Err(GenericArgCountMismatch { reported: Some(e), invalid_args: vec![] }); } - let args = create_args_for_parent_generic_args( + let args = lower_generic_args( tcx, def_id, parent_args, @@ -570,7 +567,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { (args, arg_count) } - pub fn create_args_for_associated_item( + pub fn lower_generic_args_of_assoc_item( &self, span: Span, item_def_id: DefId, @@ -581,7 +578,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { "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_generic_args_of_path( span, item_def_id, parent_args, @@ -589,9 +586,8 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { 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))); + prohibit_assoc_item_binding(self.tcx(), b.span, Some((item_segment, span))); } args @@ -603,14 +599,14 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { /// /// If the `projections` argument is `None`, then assoc type bindings like `Foo` /// are disallowed. Otherwise, they are pushed onto the vector given. - pub fn instantiate_mono_trait_ref( + pub fn lower_impl_trait_ref( &self, trait_ref: &hir::TraitRef<'tcx>, self_ty: Ty<'tcx>, ) -> ty::TraitRef<'tcx> { - self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {}); + self.prohibit_generic_args(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {}); - self.ast_path_to_mono_trait_ref( + self.lower_mono_trait_ref( trait_ref.path.span, trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()), self_ty, @@ -640,7 +636,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly, /// however. #[instrument(level = "debug", skip(self, span, constness, bounds))] - pub(crate) fn instantiate_poly_trait_ref( + pub(crate) fn lower_poly_trait_ref( &self, trait_ref: &hir::TraitRef<'tcx>, span: Span, @@ -653,10 +649,10 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()); let trait_segment = trait_ref.path.segments.last().unwrap(); - self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {}); + self.prohibit_generic_args(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_generic_args_of_path( trait_ref.path.span, trait_def_id, &[], @@ -691,7 +687,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } // 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_assoc_item_binding( trait_ref.hir_ref_id, poly_trait_ref, binding, @@ -706,7 +702,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { arg_count } - fn ast_path_to_mono_trait_ref( + fn lower_mono_trait_ref( &self, span: Span, trait_def_id: DefId, @@ -718,7 +714,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { ) -> ty::TraitRef<'tcx> { self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, is_impl); - let (generic_args, _) = self.create_args_for_ast_path( + let (generic_args, _) = self.lower_generic_args_of_path( span, trait_def_id, &[], @@ -727,12 +723,12 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { constness, ); if let Some(b) = trait_segment.args().bindings.first() { - prohibit_assoc_ty_binding(self.tcx(), b.span, Some((trait_segment, span))); + prohibit_assoc_item_binding(self.tcx(), b.span, Some((trait_segment, span))); } ty::TraitRef::new(self.tcx(), trait_def_id, generic_args) } - fn trait_defines_associated_item_named( + fn probe_trait_that_defines_assoc_item( &self, trait_def_id: DefId, assoc_kind: ty::AssocKind, @@ -744,14 +740,14 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { .is_some() } - fn ast_path_to_ty( + fn lower_path_segment( &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_generic_args_of_path_segment(span, did, item_segment); if let DefKind::TyAlias = tcx.def_kind(did) && tcx.type_alias_is_lazy(did) @@ -770,7 +766,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // 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. - fn find_bound_for_assoc_item( + fn probe_single_ty_param_bound_for_assoc_ty( &self, ty_param_def_id: LocalDefId, assoc_name: Ident, @@ -783,13 +779,12 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { ty_param_def_id, assoc_name, span, ); - let predicates = - &self.get_type_parameter_bounds(span, ty_param_def_id, assoc_name).predicates; + let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_name).predicates; debug!("find_bound_for_assoc_item: predicates={:#?}", predicates); let param_name = tcx.hir().ty_param_name(ty_param_def_id); - self.one_bound_for_assoc_item( + self.probe_single_bound_for_assoc_item( || { traits::transitive_bounds_that_define_assoc_item( tcx, @@ -811,7 +806,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // 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( + fn probe_single_bound_for_assoc_item( &self, all_candidates: impl Fn() -> I, ty_param_name: impl Display, @@ -827,7 +822,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { 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) + self.probe_trait_that_defines_assoc_item(r.def_id(), assoc_kind, assoc_name) }); let Some(bound) = matching_candidates.next() else { @@ -886,7 +881,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { match binding.kind { hir::TypeBindingKind::Equality { term } => { let term: ty::Term<'_> = match term { - hir::Term::Ty(ty) => self.ast_ty_to_ty(ty).into(), + hir::Term::Ty(ty) => self.lower_ty(ty).into(), hir::Term::Const(ct) => { ty::Const::from_anon_const(tcx, ct.def_id).into() } @@ -941,7 +936,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // 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( &self, hir_ref_id: hir::HirId, span: Span, @@ -969,7 +964,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { if let Some(variant_def) = variant_def { if permit_variants { tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None); - self.prohibit_generics(slice::from_ref(assoc_segment).iter(), |err| { + self.prohibit_generic_args(slice::from_ref(assoc_segment).iter(), |err| { err.note("enum variants can't have type parameters"); let type_name = tcx.item_name(adt_def.did()); let msg = format!( @@ -1069,7 +1064,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } } - if let Some((ty, did)) = self.lookup_inherent_assoc_ty( + if let Some((ty, did)) = self.probe_inherent_assoc_ty( assoc_ident, assoc_segment, adt_def.did(), @@ -1092,7 +1087,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { tcx.dcx().span_bug(span, "expected cycle error"); }; - self.one_bound_for_assoc_item( + self.probe_single_bound_for_assoc_item( || { traits::supertraits( tcx, @@ -1110,7 +1105,11 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { ( &ty::Param(_), Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did), - ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?, + ) => self.probe_single_ty_param_bound_for_assoc_ty( + param_did.expect_local(), + assoc_ident, + span, + )?, _ => { let reported = if variant_resolution.is_some() { // Variant in type position @@ -1172,7 +1171,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { 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_ty( span, &[qself_ty.to_string()], &traits, @@ -1185,8 +1184,8 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { }; let trait_did = bound.def_id(); - let assoc_ty_did = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, trait_did).unwrap(); - let ty = self.projected_ty_from_poly_trait_ref(span, assoc_ty_did, assoc_segment, bound); + let assoc_ty_did = self.probe_assoc_ty(assoc_ident, hir_ref_id, span, trait_did).unwrap(); + let ty = self.lower_assoc_ty(span, assoc_ty_did, assoc_segment, bound); if let Some(variant_def_id) = variant_resolution { tcx.node_span_lint( @@ -1220,7 +1219,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { Ok((ty, DefKind::AssocTy, assoc_ty_did)) } - fn lookup_inherent_assoc_ty( + fn probe_inherent_assoc_ty( &self, name: Ident, segment: &hir::PathSegment<'tcx>, @@ -1243,7 +1242,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { let candidates: Vec<_> = tcx .inherent_impls(adt_did)? .iter() - .filter_map(|&impl_| Some((impl_, self.lookup_assoc_ty_unchecked(name, block, impl_)?))) + .filter_map(|&impl_| Some((impl_, self.probe_assoc_ty_unchecked(name, block, impl_)?))) .collect(); if candidates.is_empty() { @@ -1293,7 +1292,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // `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_generic_args_of_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())), @@ -1356,7 +1355,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { .collect(); match &applicable_candidates[..] { - &[] => Err(self.complain_about_inherent_assoc_type_not_found( + &[] => Err(self.complain_about_inherent_assoc_ty_not_found( name, self_ty, candidates, @@ -1366,7 +1365,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { &[applicable_candidate] => Ok(applicable_candidate), - &[_, ..] => Err(self.complain_about_ambiguous_inherent_assoc_type( + &[_, ..] => Err(self.complain_about_ambiguous_inherent_assoc_ty( name, applicable_candidates.into_iter().map(|(_, (candidate, _))| candidate).collect(), span, @@ -1374,19 +1373,19 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } } - fn lookup_assoc_ty( + fn probe_assoc_ty( &self, name: Ident, block: hir::HirId, span: Span, scope: DefId, ) -> Option { - let (item, def_scope) = self.lookup_assoc_ty_unchecked(name, block, scope)?; + let (item, def_scope) = self.probe_assoc_ty_unchecked(name, block, scope)?; self.check_assoc_ty(item, name, def_scope, block, span); Some(item) } - fn lookup_assoc_ty_unchecked( + fn probe_assoc_ty_unchecked( &self, name: Ident, block: hir::HirId, @@ -1491,7 +1490,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { .collect() } - fn qpath_to_ty( + fn lower_qpath( &self, span: Span, opt_self_ty: Option>, @@ -1545,7 +1544,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // 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_ty( span, &type_names, &[path_str], @@ -1556,24 +1555,18 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { debug!("qpath_to_ty: self_type={:?}", self_ty); - let trait_ref = self.ast_path_to_mono_trait_ref( - span, - trait_def_id, - self_ty, - trait_segment, - false, - constness, - ); + let trait_ref = + self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment, false, constness); let item_args = - self.create_args_for_associated_item(span, item_def_id, item_segment, trait_ref.args); + self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args); debug!("qpath_to_ty: trait_ref={:?}", trait_ref); Ty::new_projection(tcx, item_def_id, item_args) } - pub fn prohibit_generics<'a>( + pub fn prohibit_generic_args<'a>( &self, segments: impl Iterator> + Clone, extend: impl Fn(&mut Diag<'_>), @@ -1676,7 +1669,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { for segment in segments { // Only emit the first error to avoid overloading the user with error messages. if let Some(b) = segment.args().bindings.first() { - prohibit_assoc_ty_binding(self.tcx(), b.span, None); + prohibit_assoc_item_binding(self.tcx(), b.span, None); return true; } } @@ -1684,14 +1677,14 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } // FIXME(eddyb, varkor) handle type paths here too, not just value ones. - pub fn def_ids_for_value_path_segments( + pub fn probe_generic_path_segments( &self, segments: &[hir::PathSegment<'_>], self_ty: Option>, kind: DefKind, def_id: DefId, span: Span, - ) -> Vec { + ) -> Vec { // We need to extract the type parameters supplied by the user in // the path `path`. Due to the current setup, this is a bit of a // tricky-process; the problem is that resolve only tells us the @@ -1742,7 +1735,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { assert!(!segments.is_empty()); let last = segments.len() - 1; - let mut path_segs = vec![]; + let mut generic_segments = vec![]; match kind { // Case 1. Reference to a struct constructor. @@ -1753,7 +1746,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // Variant and struct constructors use the // generics of their parent type definition. let generics_def_id = generics.parent.unwrap_or(def_id); - path_segs.push(PathSeg(generics_def_id, last)); + generic_segments.push(GenericPathSegment(generics_def_id, last)); } // Case 2. Reference to a variant constructor. @@ -1786,33 +1779,33 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // generics of their parent type definition. (generics.parent.unwrap_or(def_id), last) }; - path_segs.push(PathSeg(generics_def_id, index)); + generic_segments.push(GenericPathSegment(generics_def_id, index)); } // Case 3. Reference to a top-level value. DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static { .. } => { - path_segs.push(PathSeg(def_id, last)); + generic_segments.push(GenericPathSegment(def_id, last)); } // Case 4. Reference to a method or associated const. DefKind::AssocFn | DefKind::AssocConst => { if segments.len() >= 2 { let generics = tcx.generics_of(def_id); - path_segs.push(PathSeg(generics.parent.unwrap(), last - 1)); + generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1)); } - path_segs.push(PathSeg(def_id, last)); + generic_segments.push(GenericPathSegment(def_id, last)); } kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id), } - debug!("path_segs = {:?}", path_segs); + debug!("path_segs = {:?}", generic_segments); - path_segs + generic_segments } /// Check a type `Path` and convert it to a `Ty`. - pub fn res_to_ty( + pub fn lower_path( &self, opt_self_ty: Option>, path: &hir::Path<'tcx>, @@ -1832,10 +1825,10 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // Check for desugared `impl Trait`. assert!(tcx.is_type_alias_impl_trait(did)); let item_segment = path.segments.split_last().unwrap(); - self.prohibit_generics(item_segment.1.iter(), |err| { + self.prohibit_generic_args(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_generic_args_of_path_segment(span, did, item_segment.0); Ty::new_opaque(tcx, did, args) } Res::Def( @@ -1847,44 +1840,44 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { did, ) => { 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.prohibit_generic_args(path.segments.split_last().unwrap().1.iter(), |_| {}); + self.lower_path_segment(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. // The resulting `Ty` is type of the variant's enum for now. assert_eq!(opt_self_ty, None); - let path_segs = - self.def_ids_for_value_path_segments(path.segments, None, kind, def_id, span); - let generic_segs: FxHashSet<_> = - path_segs.iter().map(|PathSeg(_, index)| index).collect(); - self.prohibit_generics( + let generic_segments = + self.probe_generic_path_segments(path.segments, None, kind, def_id, span); + let indices: FxHashSet<_> = + generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect(); + self.prohibit_generic_args( path.segments.iter().enumerate().filter_map(|(index, seg)| { - if !generic_segs.contains(&index) { Some(seg) } else { None } + if !indices.contains(&index) { Some(seg) } else { None } }), |err| { err.note("enum variants can't have type parameters"); }, ); - let PathSeg(def_id, index) = path_segs.last().unwrap(); - self.ast_path_to_ty(span, *def_id, &path.segments[*index]) + let GenericPathSegment(def_id, index) = generic_segments.last().unwrap(); + self.lower_path_segment(span, *def_id, &path.segments[*index]) } Res::Def(DefKind::TyParam, def_id) => { assert_eq!(opt_self_ty, None); - self.prohibit_generics(path.segments.iter(), |err| { + self.prohibit_generic_args(path.segments.iter(), |err| { if let Some(span) = tcx.def_ident_span(def_id) { let name = tcx.item_name(def_id); 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. assert_eq!(opt_self_ty, None); - self.prohibit_generics(path.segments.iter(), |err| { + self.prohibit_generic_args(path.segments.iter(), |err| { if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments { err.span_suggestion_verbose( ident.span.shrink_to_hi().to(args.span_ext), @@ -1902,7 +1895,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // Try to evaluate any array length constants. let ty = tcx.at(span).type_of(def_id).instantiate_identity(); let span_of_impl = tcx.span_of_impl(def_id); - self.prohibit_generics(path.segments.iter(), |err| { + self.prohibit_generic_args(path.segments.iter(), |err| { let def_id = match *ty.kind() { ty::Adt(self_def, _) => self_def.did(), _ => return, @@ -2000,14 +1993,14 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } Res::Def(DefKind::AssocTy, def_id) => { debug_assert!(path.segments.len() >= 2); - self.prohibit_generics(path.segments[..path.segments.len() - 2].iter(), |_| {}); + self.prohibit_generic_args(path.segments[..path.segments.len() - 2].iter(), |_| {}); // HACK: until we support ``, assume all of them are. let constness = if tcx.has_attr(tcx.parent(def_id), sym::const_trait) { ty::BoundConstness::ConstIfConst } else { ty::BoundConstness::NotConst }; - self.qpath_to_ty( + self.lower_qpath( span, opt_self_ty, def_id, @@ -2018,7 +2011,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } Res::PrimTy(prim_ty) => { assert_eq!(opt_self_ty, None); - self.prohibit_generics(path.segments.iter(), |err| { + self.prohibit_generic_args(path.segments.iter(), |err| { let name = prim_ty.name_str(); for segment in path.segments { if let Some(args) = segment.args { @@ -2054,7 +2047,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // 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> { + 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)) => { @@ -2079,11 +2072,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // 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> { + 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)) => { @@ -2105,14 +2094,14 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { /// 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, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { + self.lower_ty_common(ast_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, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { + self.lower_ty_common(ast_ty, false, true) } fn check_delegation_constraints(&self, sig_id: DefId, span: Span, emit: bool) -> bool { @@ -2179,7 +2168,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { error_occured } - fn ty_from_delegation( + fn lower_delegation_ty( &self, sig_id: DefId, idx: hir::InferDelegationKind, @@ -2226,31 +2215,26 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { /// 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. #[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_common(&self, ast_ty: &hir::Ty<'tcx>, borrowed: bool, in_path: bool) -> Ty<'tcx> { let tcx = self.tcx(); let result_ty = match &ast_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, ast_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_lifetime(region, None); debug!(?r); - let t = self.ast_ty_to_ty_inner(mt.ty, true, false); + let t = self.lower_ty_common(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::AnonAdt(item_id) => { let did = item_id.owner_id.def_id; @@ -2270,7 +2254,14 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { 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( + ast_ty.hir_id, + bf.unsafety, + bf.abi, + bf.decl, + None, + Some(ast_ty), + ), ) } hir::TyKind::TraitObject(bounds, lifetime, repr) => { @@ -2280,7 +2271,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { TraitObjectSyntax::DynStar => ty::DynStar, }; - self.conv_object_ty_poly_trait_ref( + self.lower_trait_object_ty( ast_ty.span, ast_ty.hir_id, bounds, @@ -2291,8 +2282,8 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } 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_path(opt_self_ty, path, ast_ty.hir_id, false) } &hir::TyKind::OpaqueDef(item_id, lifetimes, in_trait) => { let opaque_ty = tcx.hir().item(item_id); @@ -2308,21 +2299,21 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } else { local_def_id.to_def_id() }; - self.impl_trait_ty_to_ty(def_id, lifetimes, in_trait) + self.lower_opaque_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_common(qself, false, true); + self.lower_assoc_path(ast_ty.hir_id, ast_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_generic_args_of_path( span, def_id, &[], @@ -2340,7 +2331,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } }; - 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 => { @@ -2358,7 +2349,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } #[instrument(level = "debug", skip(self), ret)] - fn impl_trait_ty_to_ty( + fn lower_opaque_ty( &self, def_id: DefId, lifetimes: &[hir::GenericArg<'_>], @@ -2390,7 +2381,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { &lifetimes[i] ) }; - self.ast_region_to_region(lifetime, None).into() + self.lower_lifetime(lifetime, None).into() } else { tcx.mk_param_from_def(param) } @@ -2404,18 +2395,18 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } } - 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 let Some(expected_ty) = expected_ty => { self.record_ty(ty.hir_id, expected_ty, ty.span); expected_ty } - _ => 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, @@ -2448,7 +2439,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { .enumerate() .map(|(i, a)| { if let hir::TyKind::Infer = a.kind - && !self.allow_ty_infer() + && !self.allow_infer() { if let Some(suggested_ty) = self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i)) @@ -2464,14 +2455,14 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // 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(); let output_ty = match decl.output { hir::FnRetTy::Return(output) => { if let hir::TyKind::Infer = output.kind - && !self.allow_ty_infer() + && !self.allow_infer() && let Some(suggested_ty) = self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, None) { @@ -2479,7 +2470,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { 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), @@ -2490,7 +2481,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi); let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars); - if !self.allow_ty_infer() && !(visitor.0.is_empty() && infer_replacements.is_empty()) { + if !self.allow_infer() && !(visitor.0.is_empty() && infer_replacements.is_empty()) { // We always collect the spans for placeholder types when evaluating `fn`s, but we // only want to emit an error complaining about them if infer types (`_`) are not // allowed. `allow_ty_infer` gates this behavior. We check for the presence of @@ -2562,8 +2553,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { }; let i = tcx.parent_hir_node(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)); + let trait_ref = self.lower_impl_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, diff --git a/compiler/rustc_hir_analysis/src/astconv/object_safety.rs b/compiler/rustc_hir_analysis/src/astconv/object_safety.rs index 70c60e3994188..140055cf76410 100644 --- a/compiler/rustc_hir_analysis/src/astconv/object_safety.rs +++ b/compiler/rustc_hir_analysis/src/astconv/object_safety.rs @@ -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<'tcx> dyn AstConv<'tcx> + '_ { - pub(super) fn conv_object_ty_poly_trait_ref( +impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { + pub(super) fn lower_trait_object_ty( &self, span: Span, hir_id: hir::HirId, @@ -37,7 +37,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { correct: Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }), .. - } = self.instantiate_poly_trait_ref( + } = self.lower_poly_trait_ref( &trait_bound.trait_ref, trait_bound.span, ty::BoundConstness::NotConst, @@ -133,7 +133,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // 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, @@ -231,7 +231,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { def_ids.retain(|def_id| !tcx.generics_require_sized_self(def_id)); } - self.complain_about_missing_associated_types( + self.complain_about_missing_assoc_tys( associated_types, potential_assoc_types, hir_trait_bounds, @@ -362,11 +362,11 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // Use explicitly-specified region bound. let region_bound = if !lifetime.is_elided() { - self.ast_region_to_region(lifetime, None) + self.lower_lifetime(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_lifetime(lifetime, None) } else { self.re_infer(None, span).unwrap_or_else(|| { let err = struct_span_code_err!( diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index b5377e40bfdd9..e466fc5e44ee8 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -1866,7 +1866,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 6c3f99ccc1219..06e7576e89751 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -40,7 +40,7 @@ use std::cell::Cell; use std::iter; use std::ops::Bound; -use crate::astconv::AstConv; +use crate::astconv::HirTyLowerer; use crate::check::intrinsic::intrinsic_operation_unsafety; use crate::errors; pub use type_of::test_opaque_hidden_types; @@ -277,7 +277,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); } @@ -315,12 +315,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); } } @@ -344,8 +344,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, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { + self.lowerer().lower_ty(ast_ty) } pub fn hir_id(&self) -> hir::HirId { @@ -364,7 +364,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 } @@ -373,7 +373,7 @@ impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> { self.item_def_id.to_def_id() } - fn get_type_parameter_bounds( + fn probe_ty_param_bounds( &self, span: Span, def_id: LocalDefId, @@ -386,7 +386,7 @@ impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> { None } - fn allow_ty_infer(&self) -> bool { + fn allow_infer(&self) -> bool { false } @@ -404,7 +404,7 @@ impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> { ty::Const::new_error_with_message(self.tcx(), ty, span, "bad placeholder constant") } - fn projected_ty_from_poly_trait_ref( + fn lower_assoc_ty( &self, span: Span, item_def_id: DefId, @@ -412,7 +412,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_generic_args_of_assoc_item( span, item_def_id, item_segment, @@ -547,7 +547,7 @@ 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()); let def_id = item_id.owner_id.def_id; @@ -591,7 +591,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); @@ -625,7 +625,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); } } @@ -668,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); @@ -717,7 +717,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); @@ -746,13 +746,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); @@ -788,7 +788,7 @@ 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()); } } } @@ -975,7 +975,7 @@ impl<'tcx> FieldUniquenessCheckContext<'tcx> { } } -fn convert_variant( +fn lower_variant( tcx: TyCtxt<'_>, variant_did: Option, ident: Ident, @@ -1060,7 +1060,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, @@ -1080,7 +1080,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, @@ -1284,7 +1284,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); @@ -1411,7 +1416,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, @@ -1554,9 +1559,9 @@ fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option( }; 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 diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index f914f1f9b17c3..b4e113d47ede2 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::astconv::{HirTyLowerer, PredicateFilter}; use rustc_data_structures::fx::FxIndexSet; use rustc_hir as hir; use rustc_infer::traits::util; @@ -29,9 +29,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, filter); + let mut bounds = icx.lowerer().lower_mono_bounds(item_ty, ast_bounds, filter); // 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_sized_bound(&mut bounds, item_ty, ast_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); @@ -69,9 +69,9 @@ fn opaque_type_bounds<'tcx>( ) -> &'tcx [(ty::Clause<'tcx>, Span)] { ty::print::with_reduced_queries!({ let icx = ItemCtxt::new(tcx, opaque_def_id); - let mut bounds = icx.astconv().compute_bounds(item_ty, ast_bounds, filter); + let mut bounds = icx.lowerer().lower_mono_bounds(item_ty, ast_bounds, filter); // 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_sized_bound(&mut bounds, item_ty, ast_bounds, None, span); debug!(?bounds); tcx.arena.alloc_from_iter(bounds.clauses()) diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 66c9fb93500f6..4c4cf9fa1b689 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -1,4 +1,4 @@ -use crate::astconv::{AstConv, OnlySelfBounds, PredicateFilter}; +use crate::astconv::{HirTyLowerer, OnlySelfBounds, PredicateFilter}; use crate::bounds::Bounds; use crate::collect::ItemCtxt; use crate::constrained_generic_params as cgp; @@ -149,8 +149,8 @@ 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() - .compute_bounds(tcx.types.self_param, self_bounds, PredicateFilter::All) + icx.lowerer() + .lower_mono_bounds(tcx.types.self_param, self_bounds, PredicateFilter::All) .clauses(), ); } @@ -175,10 +175,10 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen // 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_sized_bound( &mut bounds, param_ty, &[], @@ -194,7 +194,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, @@ -208,7 +208,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen for predicate in ast_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` @@ -232,7 +232,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen } let mut bounds = Bounds::default(); - icx.astconv().add_bounds( + icx.lowerer().lower_poly_bounds( ty, bound_pred.bounds.iter(), &mut bounds, @@ -243,11 +243,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_lifetime(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_lifetime(lt, None), lt.ident.span) } bound => { span_bug!( @@ -601,9 +601,9 @@ 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().lower_mono_bounds(self_param_ty, bounds, filter); - let where_bounds_that_match = icx.type_parameter_bounds_in_generics( + let where_bounds_that_match = icx.probe_ty_param_bounds_in_generics( generics, item.owner_id.def_id, self_param_ty, @@ -676,7 +676,7 @@ pub(super) fn type_param_predicates( let mut result = parent .map(|parent| { let icx = ItemCtxt::new(tcx, parent); - icx.get_type_parameter_bounds(DUMMY_SP, def_id, assoc_name) + icx.probe_ty_param_bounds(DUMMY_SP, def_id, assoc_name) }) .unwrap_or_default(); let mut extend = None; @@ -696,7 +696,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( + icx.probe_ty_param_bounds_in_generics( ast_generics, def_id, ty, @@ -719,7 +719,7 @@ impl<'tcx> ItemCtxt<'tcx> { /// 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))] - fn type_parameter_bounds_in_generics( + fn probe_ty_param_bounds_in_generics( &self, ast_generics: &'tcx hir::Generics<'tcx>, param_def_id: LocalDefId, @@ -750,13 +750,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().lower_poly_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 86b075a84a703..83877bff98ce8 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -1923,12 +1923,12 @@ fn is_late_bound_map( /// 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 ty::Ty; - impl<'tcx> TypeVisitor> for ConstrainedCollectorPostAstConv { + impl<'tcx> TypeVisitor> for ConstrainedCollectorPostHirTyLowering { fn visit_ty(&mut self, t: Ty<'tcx>) { match t.kind() { ty::Param(param_ty) => { @@ -1973,7 +1973,7 @@ fn is_late_bound_map( // See comments on `ConstrainedCollectorPostAstConv` 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 cec01abae4b55..4d8e0e04c7395 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -108,7 +108,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { .unwrap() .0 .def_id; - let ty = ItemCtxt::new(tcx, item_def_id).to_ty(hir_ty); + let ty = ItemCtxt::new(tcx, item_def_id).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 @@ -369,8 +369,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"); } @@ -392,7 +392,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder { @@ -400,7 +400,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 @@ -434,7 +434,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); @@ -466,7 +466,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()), }, @@ -480,7 +480,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) @@ -495,7 +495,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 5fe8d1fe586bc..e95ed554a78c8 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -213,10 +213,10 @@ pub fn check_crate(tcx: TyCtxt<'_>) -> Result<(), ErrorGuaranteed> { /// 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> { +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); - collect::ItemCtxt::new(tcx, env_def_id.def_id).to_ty(hir_ty) + collect::ItemCtxt::new(tcx, env_def_id.def_id).lower_ty(hir_ty) } diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index b32c5e2c3573f..752fe2a4d97ba 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::astconv::HirTyLowerer; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes}; use rustc_infer::infer::{InferOk, InferResult}; @@ -784,7 +784,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { decl: &hir::FnDecl<'tcx>, closure_kind: hir::ClosureKind, ) -> ty::PolyFnSig<'tcx> { - let astconv = self.astconv(); + let lowerer = self.lowerer(); trace!("decl = {:#?}", decl); debug!(?closure_kind); @@ -793,9 +793,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 @@ -813,7 +813,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. @@ -832,7 +832,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()) } }, }; @@ -989,17 +989,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { decl: &hir::FnDecl<'tcx>, guar: ErrorGuaranteed, ) -> ty::PolyFnSig<'tcx> { - let astconv = self.astconv(); + 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 792359c9dda1b..bed0fee6c945c 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -41,7 +41,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::astconv::HirTyLowerer; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::{Coercion, DefineOpaqueTypes, InferOk, InferResult}; use rustc_infer::traits::TraitEngine; diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 4c01c201ad238..c5aab115dbf05 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -35,7 +35,7 @@ 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::astconv::HirTyLowerer as _; use rustc_hir_analysis::check::ty_kind_suggestion; use rustc_infer::infer; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; @@ -333,7 +333,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } ExprKind::Cast(e, t) => self.check_expr_cast(e, t, expr), ExprKind::Type(e, t) => { - let ascribed_ty = self.to_ty_saving_user_provided_ty(t); + let ascribed_ty = self.lower_ty_saving_user_provided_ty(t); let ty = self.check_expr_with_hint(e, ascribed_ty); self.demand_eqtype(e.span, ascribed_ty, ty); ascribed_ty @@ -1375,7 +1375,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> Ty<'tcx> { // Find the type of `e`. Supply hints based on the type we are casting to, // if appropriate. - let t_cast = self.to_ty_saving_user_provided_ty(t); + let t_cast = self.lower_ty_saving_user_provided_ty(t); let t_cast = self.resolve_vars_if_possible(t_cast); let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast)); let t_expr = self.resolve_vars_if_possible(t_expr); @@ -1503,7 +1503,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr: &'tcx hir::Expr<'tcx>, ) -> Ty<'tcx> { let tcx = self.tcx; - let count = self.array_length_to_const(count); + let count = self.lower_array_length(count); if let Some(count) = count.try_eval_target_usize(tcx, self.param_env) { self.suggest_array_len(expr, count); } @@ -3283,7 +3283,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fields: &[Ident], expr: &'tcx hir::Expr<'tcx>, ) -> Ty<'tcx> { - let container = self.to_ty(container).normalized; + let container = self.lower_ty(container).normalized; if let Some(ident_2) = fields.get(1) && !self.tcx.features().offset_of_nested diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 1d885b801d987..c7d88438fbe08 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -11,12 +11,10 @@ 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::{ - check_generic_arg_count_for_call, create_args_for_parent_generic_args, -}; +use rustc_hir_analysis::astconv::generics::{check_generic_arg_count_for_call, lower_generic_args}; use rustc_hir_analysis::astconv::{ - AstConv, CreateInstantiationsForGenericArgsCtxt, ExplicitLateBound, GenericArgCountMismatch, - GenericArgCountResult, IsMethodCall, PathSeg, + ExplicitLateBound, GenericArgCountMismatch, GenericArgCountResult, GenericArgsLowerer, + GenericPathSegment, HirTyLowerer, IsMethodCall, }; use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse}; use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282; @@ -394,14 +392,14 @@ 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); + pub fn lower_ty(&self, ast_t: &hir::Ty<'tcx>) -> LoweredTy<'tcx> { + 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) } - pub fn to_ty_saving_user_provided_ty(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { - let ty = self.to_ty(ast_ty); + pub fn lower_ty_saving_user_provided_ty(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { + let ty = self.lower_ty(ast_ty); debug!("to_ty_saving_user_provided_ty: ty={:?}", ty); if Self::can_contain_user_lifetime_bounds(ty.raw) { @@ -424,7 +422,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn array_length_to_const(&self, length: &hir::ArrayLen) -> ty::Const<'tcx> { + pub fn lower_array_length(&self, length: &hir::ArrayLen) -> ty::Const<'tcx> { match length { hir::ArrayLen::Infer(inf) => self.ct_infer(self.tcx.types.usize, None, inf.span), hir::ArrayLen::Body(anon_const) => { @@ -436,11 +434,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn const_arg_to_const( - &self, - ast_c: &hir::AnonConst, - param_def_id: DefId, - ) -> ty::Const<'tcx> { + pub fn lower_const_arg(&self, ast_c: &hir::AnonConst, param_def_id: DefId) -> ty::Const<'tcx> { let did = ast_c.def_id; self.tcx.feed_anon_const_type(did, self.tcx.type_of(param_def_id)); let c = ty::Const::from_anon_const(self.tcx, did); @@ -827,7 +821,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { QPath::Resolved(ref opt_qself, path) => { return ( path.res, - opt_qself.as_ref().map(|qself| self.to_ty(qself)), + opt_qself.as_ref().map(|qself| self.lower_ty(qself)), path.segments, ); } @@ -841,7 +835,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(..) => { @@ -1119,9 +1113,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> (Ty<'tcx>, Res) { let tcx = self.tcx; - let path_segs = match res { + let generic_segments = 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().probe_generic_path_segments( segments, self_ty.map(|ty| ty.raw), kind, @@ -1178,14 +1172,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // provided (if any) into their appropriate spaces. We'll also report // 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 indices: FxHashSet<_> = + generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect(); + let generics_has_err = self.lowerer().prohibit_generic_args( segments.iter().enumerate().filter_map(|(index, seg)| { - if !generic_segs.contains(&index) || is_alias_variant_ctor { - Some(seg) - } else { - None - } + if !indices.contains(&index) || is_alias_variant_ctor { Some(seg) } else { None } }), |_| {}, ); @@ -1212,7 +1203,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut infer_args_for_err = FxHashSet::default(); let mut explicit_late_bound = ExplicitLateBound::No; - for &PathSeg(def_id, index) in &path_segs { + for &GenericPathSegment(def_id, index) in &generic_segments { let seg = &segments[index]; let generics = tcx.generics_of(def_id); @@ -1233,8 +1224,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - let has_self = - path_segs.last().is_some_and(|PathSeg(def_id, _)| tcx.generics_of(*def_id).has_self); + let has_self = generic_segments + .last() + .is_some_and(|GenericPathSegment(def_id, _)| tcx.generics_of(*def_id).has_self); let (res, self_ctor_args) = if let Res::SelfCtor(impl_def_id) = res { let ty = LoweredTy::from_raw( @@ -1294,22 +1286,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }, }; - struct CreateCtorInstantiationsContext<'a, 'tcx> { + struct CtorGenericArgsCtxt<'a, 'tcx> { fcx: &'a FnCtxt<'a, 'tcx>, span: Span, - path_segs: &'a [PathSeg], + generic_segments: &'a [GenericPathSegment], infer_args_for_err: &'a FxHashSet, segments: &'tcx [hir::PathSegment<'tcx>], } - impl<'tcx, 'a> CreateInstantiationsForGenericArgsCtxt<'a, 'tcx> - for CreateCtorInstantiationsContext<'a, 'tcx> - { + impl<'tcx, 'a> GenericArgsLowerer<'a, 'tcx> for CtorGenericArgsCtxt<'a, 'tcx> { fn args_for_def_id( &mut self, def_id: DefId, ) -> (Option<&'a hir::GenericArgs<'tcx>>, bool) { - if let Some(&PathSeg(_, index)) = - self.path_segs.iter().find(|&PathSeg(did, _)| *did == def_id) + if let Some(&GenericPathSegment(_, index)) = + self.generic_segments.iter().find(|&GenericPathSegment(did, _)| *did == def_id) { // If we've encountered an `impl Trait`-related error, we're just // going to infer the arguments for better error messages. @@ -1332,13 +1322,13 @@ 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_lifetime(lt, Some(param)).into() } (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => { - self.fcx.to_ty(ty).raw.into() + self.fcx.lower_ty(ty).raw.into() } (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => { - self.fcx.const_arg_to_const(&ct.value, param.def_id).into() + self.fcx.lower_const_arg(&ct.value, param.def_id).into() } (GenericParamDefKind::Type { .. }, GenericArg::Infer(inf)) => { self.fcx.ty_infer(Some(param), inf.span).into() @@ -1420,17 +1410,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let args_raw = self_ctor_args.unwrap_or_else(|| { - create_args_for_parent_generic_args( + lower_generic_args( tcx, def_id, &[], has_self, self_ty.map(|s| s.raw), &arg_count, - &mut CreateCtorInstantiationsContext { + &mut CtorGenericArgsCtxt { fcx: self, span, - path_segs: &path_segs, + generic_segments: &generic_segments, infer_args_for_err: &infer_args_for_err, segments, }, diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 19f839b6240c6..f1c6c8bef0b6e 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -24,7 +24,7 @@ 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::astconv::HirTyLowerer; use rustc_hir_analysis::check::intrinsicck::InlineAsmCtxt; use rustc_hir_analysis::check::potentially_plural_count; use rustc_hir_analysis::structured_errors::StructuredDiag; @@ -1961,16 +1961,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> (Res, LoweredTy<'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 self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself).raw); + let ty = self.lowerer().lower_path(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 ty = self.lower_ty(qself); let result = self - .astconv() - .associated_path_to_ty(hir_id, path_span, ty.raw, qself, segment, true); + .lowerer() + .lower_assoc_path(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 1850463194dc8..7922c0bfc9638 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -12,7 +12,7 @@ use hir::def_id::CRATE_DEF_ID; 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::astconv::HirTyLowerer; use rustc_infer::infer; use rustc_infer::infer::error_reporting::sub_relations::SubRelations; use rustc_infer::infer::error_reporting::TypeErrCtxt; @@ -212,7 +212,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 } @@ -221,7 +221,7 @@ impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> { self.body_id.to_def_id() } - fn get_type_parameter_bounds( + fn probe_ty_param_bounds( &self, _: Span, def_id: LocalDefId, @@ -256,7 +256,7 @@ impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> { Some(self.next_region_var(v)) } - fn allow_ty_infer(&self) -> bool { + fn allow_infer(&self) -> bool { true } @@ -292,7 +292,7 @@ impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> { } } - fn projected_ty_from_poly_trait_ref( + fn lower_assoc_ty( &self, span: Span, item_def_id: DefId, @@ -305,7 +305,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_generic_args_of_assoc_item( span, item_def_id, item_segment, diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index f4090feee1721..13ac1de7b36cd 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::astconv::HirTyLowerer; use rustc_infer::traits::{self}; use rustc_middle::lint::in_external_macro; use rustc_middle::middle::stability::EvalResult; @@ -877,7 +877,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()); @@ -958,7 +958,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .. }) => { // 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); + let ty = self.lowerer().lower_ty(bounded_ty); Some((ty, bounds)) } _ => None, @@ -996,7 +996,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) }); @@ -1071,7 +1071,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let can_return = match fn_decl.output { hir::FnRetTy::Return(ty) => { - 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/gather_locals.rs b/compiler/rustc_hir_typeck/src/gather_locals.rs index 6dae1fab6dcde..8fddccab5bf50 100644 --- a/compiler/rustc_hir_typeck/src/gather_locals.rs +++ b/compiler/rustc_hir_typeck/src/gather_locals.rs @@ -93,7 +93,7 @@ impl<'a, 'tcx> GatherLocalsVisitor<'a, 'tcx> { fn declare(&mut self, decl: Declaration<'tcx>) { let local_ty = match decl.ty { Some(ref ty) => { - let o_ty = self.fcx.to_ty(ty); + let o_ty = self.fcx.lower_ty(ty); let c_ty = self.fcx.inh.infcx.canonicalize_user_type_annotation(UserType::Ty(o_ty.raw)); diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index d259e71f95766..0cba6f538f0f7 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -57,7 +57,7 @@ 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::astconv::HirTyLowerer; use rustc_hir_analysis::check::check_abi; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::traits::{ObligationCauseCode, ObligationInspector, WellFormedLoc}; @@ -178,7 +178,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 a580c114f2614..361d38baf323a 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -4,10 +4,8 @@ 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::{ - check_generic_arg_count_for_call, create_args_for_parent_generic_args, -}; -use rustc_hir_analysis::astconv::{AstConv, CreateInstantiationsForGenericArgsCtxt, IsMethodCall}; +use rustc_hir_analysis::astconv::generics::{check_generic_arg_count_for_call, lower_generic_args}; +use rustc_hir_analysis::astconv::{GenericArgsLowerer, HirTyLowerer, IsMethodCall}; use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk}; use rustc_middle::traits::{ObligationCauseCode, UnifyReceiverContext}; use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCoercion}; @@ -366,14 +364,12 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // combining parameters from the type and those from the method. assert_eq!(generics.parent_count, parent_args.len()); - struct MethodInstantiationsCtxt<'a, 'tcx> { + struct GenericArgsCtxt<'a, 'tcx> { cfcx: &'a ConfirmContext<'a, 'tcx>, pick: &'a probe::Pick<'tcx>, seg: &'a hir::PathSegment<'tcx>, } - impl<'a, 'tcx> CreateInstantiationsForGenericArgsCtxt<'a, 'tcx> - for MethodInstantiationsCtxt<'a, 'tcx> - { + impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsCtxt<'a, 'tcx> { fn args_for_def_id( &mut self, def_id: DefId, @@ -393,13 +389,13 @@ 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_lifetime(lt, Some(param)).into() } (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => { - self.cfcx.to_ty(ty).raw.into() + self.cfcx.lower_ty(ty).raw.into() } (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => { - self.cfcx.const_arg_to_const(&ct.value, param.def_id).into() + self.cfcx.lower_const_arg(&ct.value, param.def_id).into() } (GenericParamDefKind::Type { .. }, GenericArg::Infer(inf)) => { self.cfcx.ty_infer(Some(param), inf.span).into() @@ -432,14 +428,14 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { } } - let args = create_args_for_parent_generic_args( + let args = lower_generic_args( self.tcx, pick.item.def_id, parent_args, false, None, &arg_count_correct, - &mut MethodInstantiationsCtxt { cfcx: self, pick, seg }, + &mut GenericArgsCtxt { cfcx: self, pick, seg }, ); // When the method is confirmed, the `args` includes diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index cc8b8f72cf359..c875d3da47e5f 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::{IsFirstInputType, OrphanCheckErr, OverlapResult}; pub use self::engine::{ObligationCtxt, TraitEngineExt}; pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation}; pub use self::normalize::NormalizeExt; -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 1816b98a636c6..013f6e1648145 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -36,7 +36,7 @@ pub use crate::traits::{MethodViolationCode, ObjectSafetyViolation}; /// astconv -- currently, `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 { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 810a870c35c65..cd0a7d684370a 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; @@ -1260,12 +1260,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), @@ -1306,12 +1302,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_, @@ -1690,7 +1682,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)) @@ -1716,7 +1708,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() { @@ -2742,12 +2734,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/clippy_lints/src/implicit_hasher.rs b/src/tools/clippy/clippy_lints/src/implicit_hasher.rs index a79bf66ae0133..8acb138332cfb 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::Diag; 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 74582f7f1de23..9f4d7b51271b0 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 @@ -6,7 +6,7 @@ use rustc_hir::{ GenericArg, GenericBound, GenericBounds, ItemKind, PredicateOrigin, TraitBoundModifier, TyKind, TypeBinding, WherePredicate, }; -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; @@ -146,7 +146,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..9729c971672c4 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; @@ -59,7 +59,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'tcx>, qpath: // Reallocation of a fat pointer causes it to become thin. `hir_ty_to_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 7926738d68f1a..29996a6f783e1 100644 --- a/src/tools/clippy/clippy_lints/src/types/vec_box.rs +++ b/src/tools/clippy/clippy_lints/src/types/vec_box.rs @@ -4,7 +4,7 @@ use clippy_utils::source::snippet; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, GenericArg, LangItem, 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; @@ -35,7 +35,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()) @@ -55,7 +55,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 d638af2b78b36..8764e3006c6b9 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 b28037db1121e..dfa816963bc07 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, 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_middle::ty::Ty as MiddleTy; use rustc_session::impl_lint_pass; @@ -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) } && let impl_ty = cx.tcx.type_of(impl_id).instantiate_identity() && same_type_and_consts(ty, impl_ty) 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 4aaf3b0a0b674..d1f7c6417c7e1 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)) } From 82c2c8deb1fb7640fedfbc49b5647957a1d572db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Sun, 11 Feb 2024 09:22:52 +0100 Subject: [PATCH 2/6] Update (doc) comments Several (doc) comments were super outdated or didn't provide enough context. Some doc comments shoved everything in a single paragraph without respecting the fact that the first paragraph should be a single sentence because rustdoc treats these as item descriptions / synopses on module pages. --- compiler/rustc_ast/src/ast.rs | 4 - compiler/rustc_ast/src/visit.rs | 2 +- compiler/rustc_ast_lowering/src/delegation.rs | 7 +- compiler/rustc_ast_lowering/src/item.rs | 4 +- compiler/rustc_hir/src/hir.rs | 8 +- .../rustc_hir_analysis/src/astconv/bounds.rs | 103 +++--- .../src/astconv/generics.rs | 28 +- .../rustc_hir_analysis/src/astconv/mod.rs | 299 ++++++++++++------ .../src/astconv/object_safety.rs | 1 + compiler/rustc_hir_analysis/src/bounds.rs | 4 +- .../rustc_hir_analysis/src/check/check.rs | 4 +- .../src/check/compare_impl_item.rs | 2 +- .../rustc_hir_analysis/src/check/region.rs | 2 +- .../rustc_hir_analysis/src/check/wfcheck.rs | 2 +- compiler/rustc_hir_analysis/src/collect.rs | 16 +- .../src/collect/item_bounds.rs | 4 +- .../src/collect/predicates_of.rs | 21 +- .../src/collect/resolve_bound_vars.rs | 6 +- .../rustc_hir_analysis/src/collect/type_of.rs | 6 +- compiler/rustc_hir_analysis/src/lib.rs | 16 +- .../src/variance/constraints.rs | 2 +- .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 2 +- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 4 +- .../src/fn_ctxt/suggestions.rs | 2 +- compiler/rustc_span/src/hygiene.rs | 2 +- .../src/solve/normalizes_to/inherent.rs | 2 +- .../src/traits/object_safety.rs | 5 +- .../src/traits/select/confirmation.rs | 2 +- .../traits/specialize/specialization_graph.rs | 2 +- compiler/rustc_type_ir/src/ty_kind.rs | 2 +- .../book/src/development/type_checking.md | 10 +- .../src/types/redundant_allocation.rs | 2 +- src/tools/clippy/clippy_lints/src/use_self.rs | 2 +- src/tools/clippy/tests/ui/crashes/ice-6179.rs | 2 +- tests/ui/issues/issue-17361.rs | 2 +- tests/ui/traits/alias/self-in-generics.rs | 2 +- 36 files changed, 332 insertions(+), 252 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index e4096e244e103..ea73f88dacf70 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -303,10 +303,6 @@ impl TraitBoundModifiers { }; } -/// The AST represents all type param bounds as types. -/// `typeck::collect::compute_bounds` matches these against -/// the "special" built-in traits (see `middle::lang_items`) and -/// detects `Copy`, `Send` and `Sync`. #[derive(Clone, Encodable, Decodable, Debug)] pub enum GenericBound { Trait(PolyTraitRef, TraitBoundModifiers), diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index 7bdbf48a81f21..dedf67e6a94d7 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -480,7 +480,7 @@ pub fn walk_use_tree<'a, V: Visitor<'a>>( try_visit!(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. visit_opt!(visitor, visit_ident, rename); } UseTreeKind::Glob => {} diff --git a/compiler/rustc_ast_lowering/src/delegation.rs b/compiler/rustc_ast_lowering/src/delegation.rs index 4e1c477a3d771..e26a65c1f29c8 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}; @@ -129,7 +130,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 2d03c854bd088..c9786328565ba 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1427,8 +1427,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_implicit_sized_bound` + // 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_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 21aec11b314f1..87e21785c8c93 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -428,10 +428,6 @@ pub enum TraitBoundModifier { MaybeConst, } -/// The AST represents all type param bounds as types. -/// `typeck::collect::compute_bounds` matches these against -/// the "special" built-in traits (see `middle::lang_items`) and -/// detects `Copy`, `Send` and `Sync`. #[derive(Clone, Copy, Debug, HashStable_Generic)] pub enum GenericBound<'hir> { Trait(PolyTraitRef<'hir>, TraitBoundModifier), @@ -1860,7 +1856,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. @@ -2293,7 +2289,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/astconv/bounds.rs b/compiler/rustc_hir_analysis/src/astconv/bounds.rs index dd11f58ca1982..1fe7baaa25078 100644 --- a/compiler/rustc_hir_analysis/src/astconv/bounds.rs +++ b/compiler/rustc_hir_analysis/src/astconv/bounds.rs @@ -17,7 +17,9 @@ use crate::bounds::Bounds; use crate::errors; impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { - /// Sets `implicitly_sized` to true on `Bounds` if necessary + /// Add a `Sized` bound to the `bounds` if appropriate. + /// + /// Doesn't add the bound if the HIR bounds contain any of `Sized`, `?Sized` or `!Sized`. pub(crate) fn add_sized_bound( &self, bounds: &mut Bounds<'tcx>, @@ -101,21 +103,27 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } } - /// This helper takes a *converted* parameter type (`param_ty`) - /// and an *unconverted* list of bounds: + /// Lower HIR bounds into `bounds` given the self type `param_ty` and the overarching late-bound vars if any. + /// + /// ### Examples /// - /// ```text - /// fn foo - /// ^ ^^^^^ `ast_bounds` parameter, in HIR form - /// | - /// `param_ty`, in ty form + /// ```ignore (illustrative) + /// fn foo() where for<'a> T: Trait<'a> + Copy {} + /// // ^^^^^^^ ^ ^^^^^^^^^^^^^^^^ `ast_bounds`, in HIR form + /// // | | + /// // | `param_ty`, in ty form + /// // `bound_vars`, in ty form + /// + /// fn bar() where T: for<'a> Trait<'a> + Copy {} // no overarching `bound_vars` here! + /// // ^ ^^^^^^^^^^^^^^^^^^^^^^^^ `ast_bounds`, in HIR form + /// // | + /// // `param_ty`, in ty form /// ``` /// - /// It adds these `ast_bounds` into the `bounds` structure. + /// ### A Note on Binders /// - /// **A note on binders:** there is an implied binder around - /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref` - /// for more details. + /// There is an implied binder around `param_ty` and `ast_bounds`. + /// See `lower_poly_trait_ref` for more details. #[instrument(level = "debug", skip(self, ast_bounds, bounds))] pub(crate) fn lower_poly_bounds<'hir, I: Iterator>>( &self, @@ -170,22 +178,15 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } } - /// Translates a list of bounds from the HIR into the `Bounds` data structure. - /// The self-type for the bounds is given by `param_ty`. + /// Lower HIR bounds into `bounds` given the self type `param_ty` and *no* overarching late-bound vars. /// - /// Example: + /// ### Example /// /// ```ignore (illustrative) - /// fn foo() { } + /// fn foo() {} /// // ^ ^^^^^^^^^ ast_bounds /// // param_ty /// ``` - /// - /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be - /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the - /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`. - /// - /// `span` should be the declaration size of the parameter. pub(crate) fn lower_mono_bounds( &self, param_ty: Ty<'tcx>, @@ -227,12 +228,14 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { bounds } - /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates - /// onto `bounds`. + /// Lower an associated item binding from HIR into `bounds`. + /// + /// ### A Note on Binders /// - /// **A note on binders:** given something like `T: for<'a> Iterator`, the - /// `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. + /// Given something like `T: for<'a> Iterator`, + /// the `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, dup_bindings, path_span))] pub(super) fn lower_assoc_item_binding( &self, @@ -244,22 +247,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { path_span: Span, only_self_bounds: OnlySelfBounds, ) -> Result<(), ErrorGuaranteed> { - // Given something like `U: SomeTrait`, we want to produce a - // predicate like `::T = X`. This is somewhat - // subtle in the event that `T` is defined in a supertrait of - // `SomeTrait`, because in that case we need to upcast. - // - // That is, consider this case: - // - // ``` - // trait SubTrait: SuperTrait { } - // trait SuperTrait { type T; } - // - // ... B: SubTrait ... - // ``` - // - // We want to produce `>::T == foo`. - let tcx = self.tcx(); let assoc_kind = if binding.gen_args.parenthesized @@ -272,6 +259,14 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { ty::AssocKind::Type }; + // Given something like `U: Trait`, we want to produce a predicate like + // `::T = X`. + // This is somewhat subtle in the event that `T` is defined in a supertrait of `Trait`, + // because in that case we need to upcast. I.e., we want to produce + // `>::T == X` for `B: SubTrait` where + // + // trait SubTrait: SuperTrait {} + // trait SuperTrait { type T; } let candidate = if self.probe_trait_that_defines_assoc_item( trait_ref.def_id(), assoc_kind, @@ -449,6 +444,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { span: binding.span, })); } + // Lower an equality constraint like `Item = u32` as found in HIR bound `T: Iterator` + // to a projection predicate: `::Item = u32`. hir::TypeBindingKind::Equality { term } => { let term = match term { hir::Term::Ty(ty) => self.lower_ty(ty).into(), @@ -490,10 +487,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { }, ); - // "Desugar" a constraint like `T: Iterator` this to - // the "projection predicate" for: - // - // `::Item = u32` bounds.push_projection_bound( tcx, projection_ty @@ -501,18 +494,14 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { binding.span, ); } + // Lower a constraint like `Item: Debug` as found in HIR bound `T: Iterator` + // to a bound involving a projection: `::Item: Debug`. hir::TypeBindingKind::Constraint { bounds: ast_bounds } => { - // "Desugar" a constraint like `T: Iterator` to - // - // `::Item: Debug` - // - // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty` - // parameter to have a skipped binder. - // - // NOTE: If `only_self_bounds` is true, do NOT expand this associated - // type bound into a trait predicate, since we only want to add predicates - // for the `Self` type. + // NOTE: If `only_self_bounds` is true, do NOT expand this associated type bound into + // a trait predicate, since we only want to add predicates for the `Self` type. if !only_self_bounds.0 { + // Calling `skip_binder` is okay, because `lower_bounds` expects the `param_ty` + // parameter to have a skipped binder. let param_ty = Ty::new_alias(tcx, ty::Projection, projection_ty.skip_binder()); self.lower_poly_bounds( param_ty, diff --git a/compiler/rustc_hir_analysis/src/astconv/generics.rs b/compiler/rustc_hir_analysis/src/astconv/generics.rs index 9ad6fec22ac69..cd980526db160 100644 --- a/compiler/rustc_hir_analysis/src/astconv/generics.rs +++ b/compiler/rustc_hir_analysis/src/astconv/generics.rs @@ -143,24 +143,22 @@ fn generic_arg_mismatch_err( err.emit() } -/// Creates the relevant generic arguments -/// corresponding to a set of generic parameters. This is a -/// rather complex function. Let us try to explain the role +/// Lower generic arguments from the HIR to the [`rustc_middle::ty`] representation. +/// +/// This is a rather complex function. Let us try to explain the role /// of each of its parameters: /// -/// To start, we are given the `def_id` of the thing whose generic -/// parameters we are instantiating, and a partial set of -/// arguments `parent_args`. In general, the generic arguments -/// for an item begin with arguments for all the "parents" of -/// that item -- e.g., for a method it might include the -/// parameters from the impl. +/// To start, we are given the `def_id` of the thing whose generic parameters we +/// are creating, and a partial set of arguments `parent_args`. In general, +/// the generic arguments for an item begin with arguments for all the "parents" +/// of that item -- e.g., for a method it might include the parameters from the impl. /// /// Therefore, the method begins by walking down these parents, /// starting with the outermost parent and proceed inwards until /// it reaches `def_id`. For each parent `P`, it will check `parent_args` /// first to see if the parent's arguments are listed in there. If so, -/// we can append those and move on. Otherwise, it invokes the -/// three callback functions: +/// we can append those and move on. Otherwise, it uses the provided +/// [`GenericArgsLowerer`] `ctx` which has the following methods: /// /// - `args_for_def_id`: given the `DefId` `P`, supplies back the /// generic arguments that were given to that parent from within @@ -168,10 +166,10 @@ fn generic_arg_mismatch_err( /// might refer to the trait `Foo`, and the arguments might be /// `[T]`. The boolean value indicates whether to infer values /// for arguments whose values were not explicitly provided. -/// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`, -/// instantiate a `GenericArg`. -/// - `inferred_kind`: if no parameter was provided, and inference is enabled, then -/// creates a suitable inference variable. +/// - `provided_kind`: given the generic parameter and the value +/// from `args_for_def_id`, creating a `GenericArg`. +/// - `inferred_kind`: if no parameter was provided, and inference +/// is enabled, then creates a suitable inference variable. pub fn lower_generic_args<'tcx: 'a, 'a>( tcx: TyCtxt<'tcx>, def_id: DefId, diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index 14864da1e39cd..a9e3c3b75bd3e 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -1,6 +1,17 @@ -//! 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[^1] from the [HIR][hir] to +//! the [`rustc_middle::ty`] representation. +//! +//! Not to be confused with *AST lowering* which lowers AST constructs to HIR ones +//! or with *THIR* / *MIR* *lowering* / *building* which lowers HIR *bodies* +//! (i.e., “executable code”) to THIR / MIR. +//! +//! Most lowering routines are defined on [`dyn HirTyLowerer`](HirTyLowerer) directly, +//! like the main routine of this module, `lower_ty`. +//! +//! This module used to be called `astconv`. +//! +//! [^1]: This includes types, lifetimes / regions, constants in type positions, +//! trait references and bounds. mod bounds; mod errors; @@ -43,6 +54,7 @@ use rustc_trait_selection::traits::{self, ObligationCtxt}; use std::fmt::Display; use std::slice; +/// A path segment that is semantically allowed to have generic arguments. #[derive(Debug)] pub struct GenericPathSegment(pub DefId, pub usize); @@ -67,23 +79,30 @@ pub enum PredicateFilter { SelfAndAssociatedTypeBounds, } +/// A context which can lower type-system entities from the [HIR][hir] to +/// the [`rustc_middle::ty`] representation. +/// +/// This trait used to be called `AstConv`. pub trait HirTyLowerer<'tcx> { fn tcx(&self) -> TyCtxt<'tcx>; + /// Returns the [`DefId`] of the overarching item whose constituents get lowered. fn item_def_id(&self) -> DefId; - /// Returns predicates in scope of the form `X: Foo`, where `X` - /// is a type parameter `X` with the given id `def_id` and T - /// matches `assoc_name`. This is a subset of the full set of - /// predicates. + /// Probe bounds in scope where the bounded type coincides with the given type parameter. + /// + /// Rephrased, this returns bounds of the form `T: Trait`, where `T` is a type parameter + /// with the given `def_id`. This is a subset of the full set of bounds. + /// + /// This method may use the given `assoc_name` to disregard bounds whose trait reference + /// doesn't define an associated item with the provided name. /// - /// This is used for one specific purpose: resolving "short-hand" - /// associated type references like `T::Item`. In principle, we - /// would do that by first getting the full set of predicates in - /// scope and then filtering down to find those that apply to `T`, - /// but this can lead to cycle errors. The problem is that we have - /// to do this resolution *in order to create the predicates in - /// the first place*. Hence, we have this "special pass". + /// This is used for one specific purpose: Resolving “short-hand” associated type references + /// like `T::Item` where `T` is a type parameter. In principle, we would do that by first + /// getting the full set of predicates in scope and then filtering down to find those that + /// apply to `T`, but this can lead to cycle errors. The problem is that we have to do this + /// resolution *in order to create the predicates in the first place*. + /// Hence, we have this “special pass”. fn probe_ty_param_bounds( &self, span: Span, @@ -91,14 +110,14 @@ pub trait HirTyLowerer<'tcx> { assoc_name: Ident, ) -> ty::GenericPredicates<'tcx>; - /// Returns the lifetime to use when a lifetime is omitted (and not elided). + /// Returns the region to use when a lifetime is omitted (and not elided). fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Option>; /// Returns the type to use when a type is omitted. fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>; - /// Returns `true` if `_` is allowed in type signatures in the current context. + /// Returns `true` if the current context allows the use of inference variables. fn allow_infer(&self) -> bool; /// Returns the const to use when a const is omitted. @@ -109,13 +128,18 @@ pub trait HirTyLowerer<'tcx> { span: Span, ) -> Const<'tcx>; - /// Projecting an associated type from a (potentially) - /// higher-ranked trait reference is more complicated, because of - /// the possibility of late-bound regions appearing in the - /// associated type binding. This is not legal in function - /// signatures for that reason. In a function body, we can always - /// handle it because we can use inference variables to remove the - /// late-bound regions. + /// Lower an associated type to a projection. + /// + /// This method has to be defined by the concrete lowering context because + /// dealing with higher-ranked trait references depends on its capabilities: + /// + /// If the context can make use of type inference, it can simply instantiate + /// any late-bound vars bound by the trait reference with inference variables. + /// If it doesn't support type inference, there is nothing reasonable it can + /// do except reject the associated type. + /// + /// The canonical example of this is associated type `T::P` where `T` is a type + /// param constrained by `T: for<'a> Trait<'a>` and where `Trait` defines `P`. fn lower_assoc_ty( &self, span: Span, @@ -125,20 +149,26 @@ pub trait HirTyLowerer<'tcx> { ) -> Ty<'tcx>; /// Returns `AdtDef` if `ty` is an ADT. - /// Note that `ty` might be a projection type that needs normalization. + /// + /// Note that `ty` might be a alias 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 /// or to an enum variant depending on the result of this function. fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option>; - /// Invoked when we encounter an error from some prior pass - /// (e.g., resolve) that is translated into a ty-error. This is - /// used to help suppress derived errors typeck might otherwise - /// report. + /// Taint the context with errors. + /// + /// Invoke this when you encounter an error from some prior pass like name resolution. + /// This is used to help suppress derived errors typeck might otherwise report. fn set_tainted_by_errors(&self, e: ErrorGuaranteed); + /// Record the lowered type of a HIR node in this context. fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span); + /// Convenience method for coercing the lowering context into a trait object type. + /// + /// Most lowering routines are defined on the trait object type directly + /// necessitating a coercion step from the concrete lowering context. fn lowerer(&self) -> &dyn HirTyLowerer<'tcx> where Self: Sized, @@ -146,6 +176,7 @@ pub trait HirTyLowerer<'tcx> { self } + /// The inference context of the lowering context if applicable. fn infcx(&self) -> Option<&InferCtxt<'tcx>>; } @@ -197,6 +228,10 @@ pub struct GenericArgCountResult { pub correct: Result<(), GenericArgCountMismatch>, } +/// A context which can lower HIR's [`GenericArg`] to `rustc_middle`'s [`ty::GenericArg`]. +/// +/// Its only consumer is [`generics::lower_generic_args`]. +/// Read its documentation to learn more. pub trait GenericArgsLowerer<'a, 'tcx> { fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool); @@ -215,6 +250,7 @@ pub trait GenericArgsLowerer<'a, 'tcx> { } impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { + /// Lower a lifetime from the HIR to our internal notion of a lifetime called a *region*. #[instrument(level = "debug", skip(self), ret)] pub fn lower_lifetime( &self, @@ -271,8 +307,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } } - /// 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 lower_generic_args_of_path_segment( &self, span: Span, @@ -293,14 +327,14 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { args } - /// Given the type/lifetime/const arguments provided to some path (along with - /// an implicit `Self`, if this is a trait reference), returns the complete - /// set of generic arguments. This may involve applying defaulted type parameters. + /// Lower the generic arguments provided to some path. /// - /// Constraints on associated types are not converted here but - /// separately in `add_predicates_for_ast_type_binding`. + /// If this is a trait reference, you also need to pass the self type `self_ty`. + /// The lowering process may involve applying defaulted type parameters. /// - /// Example: + /// Associated item bindings are not handled here! + /// + /// ### Example /// /// ```ignore (illustrative) /// T: std::ops::Index @@ -589,16 +623,12 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { if let Some(b) = item_segment.args().bindings.first() { prohibit_assoc_item_binding(self.tcx(), b.span, Some((item_segment, span))); } - args } - /// Instantiates the path for the given trait reference, assuming that it's - /// bound to a valid trait type. Returns the `DefId` of the defining trait. - /// The type _cannot_ be a type other than a trait type. + /// Lower a trait reference as found in an impl header as the implementee. /// - /// If the `projections` argument is `None`, then assoc type bindings like `Foo` - /// are disallowed. Otherwise, they are pushed onto the vector given. + /// The self type `self_ty` is the implementer of the trait. pub fn lower_impl_trait_ref( &self, trait_ref: &hir::TraitRef<'tcx>, @@ -616,25 +646,29 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { ) } - /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct - /// a full trait reference. The resulting trait reference is returned. This may also generate - /// auxiliary bounds, which are added to `bounds`. + /// Lower a polymorphic trait reference given a self type into `bounds`. /// - /// Example: + /// *Polymorphic* in the sense that it may bind late-bound vars. /// - /// ```ignore (illustrative) - /// poly_trait_ref = Iterator - /// self_ty = Foo - /// ``` + /// This may generate auxiliary bounds if the trait reference contains associated item bindings. + /// + /// ### Example /// - /// this would return `Foo: Iterator` and add `::Item = u32` into `bounds`. + /// Given the trait ref `Iterator` and the self type `Ty`, this will add the + /// + /// 1. *trait predicate* `` (known as `Foo: Iterator` in surface syntax) and the + /// 2. *projection predicate* `::Item = u32` + /// + /// to `bounds`. + /// + /// ### A Note on Binders + /// + /// Against our usual convention, there is an implied binder around the `self_ty` and the + /// `trait_ref` here. So they may reference late-bound vars. /// - /// **A note on binders:** against our usual convention, there is an implied binder around - /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions. /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>` - /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be - /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly, - /// however. + /// where `'a` is a bound region at depth 0. Similarly, the `trait_ref` would be `Bar<'a>`. + /// The lowered poly-trait-ref will track this binder explicitly, however. #[instrument(level = "debug", skip(self, span, constness, bounds))] pub(crate) fn lower_poly_trait_ref( &self, @@ -702,6 +736,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { arg_count } + /// Lower a monomorphic trait reference given a self type while prohibiting associated item bindings. + /// + /// *Monomorphic* in the sense that it doesn't bind any late-bound vars. fn lower_mono_trait_ref( &self, span: Span, @@ -709,7 +746,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { 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> { self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, is_impl); @@ -762,10 +799,12 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } } - // 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 trait bound on a type parameter whose trait defines the associated type given by `assoc_name`. + /// + /// This fails if there is no such bound in the list of candidates or if there are multiple + /// candidates in which case it reports ambiguity. + /// + /// `ty_param_def_id` is the `LocalDefId` of the type parameter. fn probe_single_ty_param_bound_for_assoc_ty( &self, ty_param_def_id: LocalDefId, @@ -803,8 +842,10 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { ) } - // Checks that `bounds` contains exactly one element and reports appropriate - // errors otherwise. + /// Search for a single trait bound whose trait defines the associated item given by `assoc_name`. + /// + /// This fails if there is no such bound in the list of candidates or if there are multiple + /// candidates in which case it reports ambiguity. #[instrument(level = "debug", skip(self, all_candidates, ty_param_name, binding), ret)] fn probe_single_bound_for_assoc_item( &self, @@ -927,12 +968,31 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { 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`. + /// Lower a [type-relative] path referring to an associated type or to an enum variant. + /// + /// If the path refers to an enum variant and `permit_variants` holds, + /// the returned type is simply the provided self type `qself_ty`. + /// + /// A path like `A::B::C::D` is understood as `::D`. I.e., + /// `qself_ty` / `qself` is `A::B::C` and `assoc_segment` is `D`. + /// We return the lowered type and the `DefId` for the whole path. + /// + /// We only support associated type paths whose self type is a type parameter or a `Self` + /// type alias (in a trait impl) like `T::Ty` (where `T` is a ty param) or `Self::Ty`. + /// We **don't** support paths whose self type is an arbitrary type like `Struct::Ty` where + /// struct `Struct` impls an in-scope trait that defines an associated type called `Ty`. + /// For the latter case, we report ambiguity. + /// While desirable to support, the implemention would be non-trivial. Tracked in [#22519]. + /// + /// At the time of writing, *inherent associated types* are also resolved here. This however + /// is [problematic][iat]. A proper implementation would be as non-trivial as the one + /// described in the previous paragraph and their modeling of projections would likely be + /// very similar in nature. + /// + /// [type-relative]: hir::QPath::TypeRelative + /// [#22519]: https://github.com/rust-lang/rust/issues/22519 + /// [iat]: https://github.com/rust-lang/rust/issues/8995#issuecomment-1569208403 + // // 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)] @@ -1064,6 +1124,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } } + // FIXME(inherent_associated_types, #106719): Support self types other than ADTs. if let Some((ty, did)) = self.probe_inherent_assoc_ty( assoc_ident, assoc_segment, @@ -1233,8 +1294,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // 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) which mask the feature-gate error, needlessly confusing users + // who use IATs by accident (#113265). if !tcx.features().inherent_associated_types { return Ok(None); } @@ -1289,7 +1351,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { self.check_assoc_ty(assoc_item, name, def_scope, block, span); // FIXME(fmease): Currently creating throwaway `parent_args` to please - // `create_args_for_associated_item`. Modify the latter instead (or sth. similar) to + // `lower_generic_args_of_assoc_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.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args); @@ -1490,6 +1552,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { .collect() } + /// Lower a qualified path to a type. fn lower_qpath( &self, span: Span, @@ -1676,6 +1739,22 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { emitted } + /// Probe path segments that are semantically allowed to have generic arguments. + /// + /// ### Example + /// + /// ```ignore (illustrative) + /// Option::None::<()> + /// // ^^^^ permitted to have generic args + /// + /// // ==> [GenericPathSegment(Option_def_id, 1)] + /// + /// Option::<()>::None + /// // ^^^^^^ ^^^^ *not* permitted to have generic args + /// // permitted to have generic args + /// + /// // ==> [GenericPathSegment(Option_def_id, 0)] + /// ``` // FIXME(eddyb, varkor) handle type paths here too, not just value ones. pub fn probe_generic_path_segments( &self, @@ -1685,9 +1764,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { def_id: DefId, span: Span, ) -> Vec { - // We need to extract the type parameters supplied by the user in + // We need to extract the generic arguments supplied by the user in // the path `path`. Due to the current setup, this is a bit of a - // tricky-process; the problem is that resolve only tells us the + // tricky process; the problem is that resolve only tells us the // end-point of the path resolution, and not the intermediate steps. // Luckily, we can (at least for now) deduce the intermediate steps // just from the end-point. @@ -1698,35 +1777,35 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // // struct Foo(...) // - // In this case, the parameters are declared in the type space. + // In this case, the generic arguments are declared in the type space. // // 2. Reference to a constructor of an enum variant: // // enum E { Foo(...) } // - // In this case, the parameters are defined in the type space, + // In this case, the generic arguments are defined in the type space, // but may be specified either on the type or the variant. // - // 3. Reference to a fn item or a free constant: + // 3. Reference to a free function or constant: // - // fn foo() { } + // fn foo() {} // // In this case, the path will again always have the form - // `a::b::foo::` where only the final segment should have - // type parameters. However, in this case, those parameters are - // declared on a value, and hence are in the `FnSpace`. + // `a::b::foo::` where only the final segment should have generic + // arguments. However, in this case, those arguments are declared on + // a value, and hence are in the value space. // - // 4. Reference to a method or an associated constant: + // 4. Reference to an associated function or constant: // // impl SomeStruct { - // fn foo(...) + // fn foo(...) {} // } // - // Here we can have a path like - // `a::b::SomeStruct::::foo::`, in which case parameters - // may appear in two places. The penultimate segment, - // `SomeStruct::`, contains parameters in TypeSpace, and the - // final segment, `foo::` contains parameters in fn space. + // Here we can have a path like `a::b::SomeStruct::::foo::`, + // in which case generic arguments may appear in two places. The + // penultimate segment, `SomeStruct::`, contains generic arguments + // in the type space, and the final segment, `foo::` contains + // generic arguments in value space. // // The first step then is to categorize the segments appropriately. @@ -1804,7 +1883,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { generic_segments } - /// Check a type `Path` and convert it to a `Ty`. + /// Lower a type `Path` to a type. pub fn lower_path( &self, opt_self_ty: Option>, @@ -1844,7 +1923,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { self.lower_path_segment(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); @@ -2045,8 +2124,10 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } } - // Converts a hir id corresponding to a type parameter to - // a early-bound `ty::Param` or late-bound `ty::Bound`. + /// Lower a type parameter from the HIR to our internal notion of a type. + /// + /// Early-bound type parameters get lowered to [`ty::Param`] + /// and late-bound ones to [`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) { @@ -2070,8 +2151,10 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } } - // Converts a hir id corresponding to a const parameter to - // a early-bound `ConstKind::Param` or late-bound `ConstKind::Bound`. + /// Lower a const parameter from the HIR to our internal notion of a constant. + /// + /// Early-bound const parameters get lowered to [`ty::ConstKind::Param`] + /// and late-bound ones to [`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) { @@ -2092,14 +2175,12 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } } - /// Parses the programmer's textual representation of a type into our - /// internal notion of a type. + /// Lower a type from the HIR to our internal notion of a type. pub fn lower_ty(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { self.lower_ty_common(ast_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. + /// Lower a type inside of a path from the HIR to our internal notion of a type. pub fn lower_ty_in_path(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { self.lower_ty_common(ast_ty, false, true) } @@ -2202,8 +2283,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { sig.instantiate_identity() }; - // Bound vars are also inherited from `sig_id`. They will be - // rebinded later in `ty_of_fn`. + // Bound vars are also inherited from `sig_id`. + // They will be rebound later in `lower_fn_ty`. let sig = sig.skip_binder(); match idx { @@ -2212,8 +2293,14 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } } - /// 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. + /// Lower a type from the HIR to our internal notion of a type given some extra data for diagnostics. + /// + /// Extra diagnostic data: + /// + /// 1. `borrowed`: Whether trait object types are borrowed like in `&dyn Trait`. + /// Used to avoid emitting redundant errors. + /// 2. `in_path`: Whether the type appears inside of a path. + /// Used to provide correct diagnostics for bare trait object types. #[instrument(level = "debug", skip(self), ret)] fn lower_ty_common(&self, ast_ty: &hir::Ty<'tcx>, borrowed: bool, in_path: bool) -> Ty<'tcx> { let tcx = self.tcx(); @@ -2348,6 +2435,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { result_ty } + /// Lower an opaque type (i.e., an existential impl-Trait type) from the HIR. #[instrument(level = "debug", skip(self), ret)] fn lower_opaque_ty( &self, @@ -2405,6 +2493,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } } + /// Lower a function type from the HIR to our internal notion of a function signature. #[instrument(level = "debug", skip(self, hir_id, unsafety, abi, decl, generics, hir_ty), ret)] pub fn lower_fn_ty( &self, @@ -2484,7 +2573,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { if !self.allow_infer() && !(visitor.0.is_empty() && infer_replacements.is_empty()) { // We always collect the spans for placeholder types when evaluating `fn`s, but we // only want to emit an error complaining about them if infer types (`_`) are not - // allowed. `allow_ty_infer` gates this behavior. We check for the presence of + // allowed. `allow_infer` gates this behavior. We check for the presence of // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`. let mut diag = crate::collect::placeholder_type_error_diag( @@ -2610,7 +2699,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } /// 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/astconv/object_safety.rs index 140055cf76410..2a3f956bfba99 100644 --- a/compiler/rustc_hir_analysis/src/astconv/object_safety.rs +++ b/compiler/rustc_hir_analysis/src/astconv/object_safety.rs @@ -18,6 +18,7 @@ use smallvec::{smallvec, SmallVec}; use super::HirTyLowerer; impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { + /// Lower a trait object type from the HIR to our internal notion of a type. pub(super) fn lower_trait_object_ty( &self, span: Span, 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/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index d1fed13ee9feb..09b20917e2a02 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -382,8 +382,8 @@ fn check_opaque_meets_bounds<'tcx>( Ok(()) => {} Err(ty_err) => { // Some types may be left "stranded" if they can't be reached - // from an astconv'd bound but they're mentioned in the HIR. This - // will happen, e.g., when a nested opaque is inside of a non- + // from a lowered rustc_middle bound but they're mentioned in the HIR. + // This will happen, e.g., when a nested opaque is inside of a non- // existent associated type, like `impl Trait`. // See . let ty_err = ty_err.to_string(tcx); 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 d2fdff6177e60..8fb6569aa1471 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -746,7 +746,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 eb31e1546cfaa..e84bce92fc5da 100644 --- a/compiler/rustc_hir_analysis/src/check/region.rs +++ b/compiler/rustc_hir_analysis/src/check/region.rs @@ -760,7 +760,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 e466fc5e44ee8..2b4a35d0b9bc5 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -272,7 +272,7 @@ fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) -> Result<() } Some(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 { diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 06e7576e89751..1fa8cbd96271e 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -88,13 +88,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. /// @@ -111,11 +110,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. +/// `probe_ty_param_bounds` requests, drawing the information from +/// the HIR (`hir::Generics`), recursively. pub struct ItemCtxt<'tcx> { tcx: TyCtxt<'tcx>, item_def_id: LocalDefId, @@ -785,8 +784,7 @@ fn lower_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId) { tcx.ensure().predicates_of(f.did); } - // Convert the ctor, if any. This also registers the variant as - // an item. + // Lower the ctor, if any. This also registers the variant as an item. if let Some(ctor_def_id) = variant.ctor_def_id() { lower_variant_ctor(tcx, ctor_def_id.expect_local()); } @@ -1545,7 +1543,7 @@ fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option::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 4c4cf9fa1b689..6d90a86748623 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -542,8 +542,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, @@ -574,8 +574,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, @@ -615,7 +615,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. Same for implied predicates, which // make sure we walk into associated type bounds. @@ -656,7 +656,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`. @@ -714,10 +714,11 @@ 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. + /// 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, ast_generics))] fn probe_ty_param_bounds_in_generics( &self, 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 83877bff98ce8..27a26cfe4747f 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -1917,7 +1917,7 @@ 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. @@ -1970,8 +1970,8 @@ 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 = ConstrainedCollectorPostHirTyLowering { arg_is_constrained: vec![false; generics.params.len()].into_boxed_slice(), diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index 4d8e0e04c7395..722def2563cbd 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -97,10 +97,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) diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index e95ed554a78c8..d7fcb19a536ae 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. +- astconv: lowers type-system entities from the [HIR][hir] to the + [`rustc_middle::ty`] representation. - collect: computes the types of each top-level item and enters them into the `tcx.types` table for later use. @@ -211,8 +211,16 @@ 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. +/// 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 (`_`). +/// +/// It's used in rustdoc and Clippy. +/// +///
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 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/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index c7d88438fbe08..b8f1c0e73c0c6 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -826,7 +826,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); } QPath::TypeRelative(ref qself, ref segment) => { - // Don't use `self.to_ty`, since this will register a WF obligation. + // Don't use `self.lower_ty`, since this will register a WF obligation. // If we're trying to call a nonexistent method on a trait // (e.g. `MyTrait::missing_method`), then resolution will // give us a `QPath::TypeRelative` with a trait object as diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index 7922c0bfc9638..ed70c63ccdcdf 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -360,8 +360,8 @@ impl<'a, 'tcx> HirTyLowerer<'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 13ac1de7b36cd..a7763e91b7a47 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -957,7 +957,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { bounded_ty, .. }) => { - // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below) + // 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)) } 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 d60490bce4471..439f9eec831f2 100644 --- a/compiler/rustc_trait_selection/src/solve/normalizes_to/inherent.rs +++ b/compiler/rustc_trait_selection/src/solve/normalizes_to/inherent.rs @@ -1,5 +1,5 @@ //! 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 generic parameters, //! 2. equate the self type, and diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index 013f6e1648145..feca4d384bc38 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -32,8 +32,9 @@ 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 hir_ty_lowering_object_safety_violations( diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 6f16194d44fc3..eca36fc343e20 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -1264,7 +1264,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 95db9e2092fad..1aa65b87f0b7b 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs @@ -396,7 +396,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 de8f56618d000..c83428af50a21 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -60,7 +60,7 @@ impl 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/tools/clippy/book/src/development/type_checking.md b/src/tools/clippy/book/src/development/type_checking.md index 136b3fd027057..e6da4322a1793 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. ## Creating Types programmatically @@ -162,6 +162,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/types/redundant_allocation.rs b/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs index 9729c971672c4..37437cbfbec4a 100644 --- a/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs +++ b/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs @@ -56,7 +56,7 @@ 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 = lower_ty(cx.tcx, hir_ty); diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index dfa816963bc07..a6b411d6c0f97 100644 --- a/src/tools/clippy/clippy_lints/src/use_self.rs +++ b/src/tools/clippy/clippy_lints/src/use_self.rs @@ -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() { diff --git a/src/tools/clippy/tests/ui/crashes/ice-6179.rs b/src/tools/clippy/tests/ui/crashes/ice-6179.rs index fffc0f7d0d4f2..91160eef03df9 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)] diff --git a/tests/ui/issues/issue-17361.rs b/tests/ui/issues/issue-17361.rs index 8e85f0791d676..1b1eeb5a25243 100644 --- a/tests/ui/issues/issue-17361.rs +++ b/tests/ui/issues/issue-17361.rs @@ -1,5 +1,5 @@ //@ run-pass -// Test that astconv doesn't forget about mutability of &mut str +// Test that HIR ty lowering doesn't forget about mutability of `&mut str`. //@ pretty-expanded FIXME #23616 diff --git a/tests/ui/traits/alias/self-in-generics.rs b/tests/ui/traits/alias/self-in-generics.rs index dcb33b7a90af4..433b741532d6c 100644 --- a/tests/ui/traits/alias/self-in-generics.rs +++ b/tests/ui/traits/alias/self-in-generics.rs @@ -1,4 +1,4 @@ -// astconv uses `FreshTy(0)` as a dummy `Self` type when instanciating trait objects. +// HIR ty lowering uses `FreshTy(0)` as a dummy `Self` type when instanciating trait objects. // This `FreshTy(0)` can leak into substs, causing ICEs in several places. #![feature(trait_alias)] From b79335dbedfbb9599970c209c3f3e7a5e3e7b992 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Sun, 11 Feb 2024 09:24:35 +0100 Subject: [PATCH 3/6] Update local variables and tracing calls Most of the tracing calls didn't fully leverage the power of `tracing`. For example, several of them used to hard-code method names / tracing spans as well as variable names. Use `#[instrument]` and `?var` / `%var` (etc.) instead. In my opinion, this is the proper way to migrate them from the old AstConv nomenclature to the new HIR ty lowering one. --- .../rustc_hir_analysis/src/astconv/bounds.rs | 36 +++---- .../rustc_hir_analysis/src/astconv/mod.rs | 95 ++++++++----------- .../src/astconv/object_safety.rs | 13 ++- compiler/rustc_hir_analysis/src/collect.rs | 39 ++++---- .../src/collect/generics_of.rs | 9 +- .../src/collect/item_bounds.rs | 12 +-- .../src/collect/predicates_of.rs | 18 ++-- compiler/rustc_hir_typeck/src/expr.rs | 20 ++-- .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 31 +++--- .../rustc_hir_typeck/src/method/suggest.rs | 6 +- .../src/traits/object_safety.rs | 5 +- 11 files changed, 136 insertions(+), 148 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/astconv/bounds.rs b/compiler/rustc_hir_analysis/src/astconv/bounds.rs index 1fe7baaa25078..0404fc6ea7f9f 100644 --- a/compiler/rustc_hir_analysis/src/astconv/bounds.rs +++ b/compiler/rustc_hir_analysis/src/astconv/bounds.rs @@ -24,7 +24,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { &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, ) { @@ -35,9 +35,9 @@ impl<'tcx> dyn HirTyLowerer<'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 { @@ -60,7 +60,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } } }; - search_bounds(ast_bounds); + search_bounds(hir_bounds); if let Some((self_ty, where_clause)) = self_ty_where_predicates { for clause in where_clause { if let hir::WherePredicate::BoundPredicate(pred) = clause @@ -109,34 +109,34 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// /// ```ignore (illustrative) /// fn foo() where for<'a> T: Trait<'a> + Copy {} - /// // ^^^^^^^ ^ ^^^^^^^^^^^^^^^^ `ast_bounds`, in HIR form + /// // ^^^^^^^ ^ ^^^^^^^^^^^^^^^^ `hir_bounds`, in HIR form /// // | | /// // | `param_ty`, in ty form /// // `bound_vars`, in ty form /// /// fn bar() where T: for<'a> Trait<'a> + Copy {} // no overarching `bound_vars` here! - /// // ^ ^^^^^^^^^^^^^^^^^^^^^^^^ `ast_bounds`, in HIR form + /// // ^ ^^^^^^^^^^^^^^^^^^^^^^^^ `hir_bounds`, in HIR form /// // | /// // `param_ty`, in ty form /// ``` /// /// ### A Note on Binders /// - /// There is an implied binder around `param_ty` and `ast_bounds`. + /// There is an implied binder around `param_ty` and `hir_bounds`. /// See `lower_poly_trait_ref` for more details. - #[instrument(level = "debug", skip(self, ast_bounds, bounds))] + #[instrument(level = "debug", skip(self, hir_bounds, bounds))] pub(crate) fn lower_poly_bounds<'hir, I: Iterator>>( &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 => { @@ -183,14 +183,14 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// ### Example /// /// ```ignore (illustrative) - /// fn foo() {} - /// // ^ ^^^^^^^^^ ast_bounds + /// fn foo() { } + /// // ^ ^^^^^^^^^ hir_bounds /// // param_ty /// ``` pub(crate) fn lower_mono_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(); @@ -204,7 +204,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { self.lower_poly_bounds( param_ty, - ast_bounds.iter().filter(|bound| match filter { + hir_bounds.iter().filter(|bound| match filter { PredicateFilter::All | PredicateFilter::SelfOnly | PredicateFilter::SelfAndAssociatedTypeBounds => true, @@ -496,7 +496,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } // Lower a constraint like `Item: Debug` as found in HIR bound `T: Iterator` // to a bound involving a projection: `::Item: Debug`. - hir::TypeBindingKind::Constraint { bounds: ast_bounds } => { + hir::TypeBindingKind::Constraint { bounds: hir_bounds } => { // NOTE: If `only_self_bounds` is true, do NOT expand this associated type bound into // a trait predicate, since we only want to add predicates for the `Self` type. if !only_self_bounds.0 { @@ -505,7 +505,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let param_ty = Ty::new_alias(tcx, ty::Projection, projection_ty.skip_binder()); self.lower_poly_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/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index a9e3c3b75bd3e..8aadbb1f8335d 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -376,7 +376,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { 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() { @@ -601,6 +601,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { (args, arg_count) } + #[instrument(level = "debug", skip_all)] pub fn lower_generic_args_of_assoc_item( &self, span: Span, @@ -608,10 +609,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { 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 - ); + debug!(?span, ?item_def_id, ?item_segment); let (args, _) = self.lower_generic_args_of_path( span, item_def_id, @@ -805,22 +803,18 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// candidates in which case it reports ambiguity. /// /// `ty_param_def_id` is the `LocalDefId` of the type parameter. + #[instrument(level = "debug", skip_all, ret)] fn probe_single_ty_param_bound_for_assoc_ty( &self, ty_param_def_id: LocalDefId, assoc_name: Ident, span: Span, ) -> Result, ErrorGuaranteed> { + debug!(?ty_param_def_id, ?assoc_name, ?span); let tcx = self.tcx(); - debug!( - "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})", - ty_param_def_id, assoc_name, span, - ); - let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_name).predicates; - - debug!("find_bound_for_assoc_item: predicates={:#?}", predicates); + debug!("predicates={:#?}", predicates); let param_name = tcx.hir().ty_param_name(ty_param_def_id); self.probe_single_bound_for_assoc_item( @@ -995,7 +989,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // // NOTE: When this function starts resolving `Trait::AssocTy` successfully // it should also start reporting the `BARE_TRAIT_OBJECTS` lint. - #[instrument(level = "debug", skip(self, hir_ref_id, span, qself, assoc_segment), fields(assoc_ident=?assoc_segment.ident), ret)] + #[instrument(level = "debug", skip_all, ret)] pub fn lower_assoc_path( &self, hir_ref_id: hir::HirId, @@ -1005,7 +999,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { assoc_segment: &hir::PathSegment<'tcx>, permit_variants: bool, ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> { + 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 @@ -1553,6 +1549,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } /// Lower a qualified path to a type. + #[instrument(level = "debug", skip_all)] fn lower_qpath( &self, span: Span, @@ -1565,22 +1562,19 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { 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. @@ -1615,17 +1609,15 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { ); return Ty::new_error(tcx, reported); }; - - debug!("qpath_to_ty: self_type={:?}", self_ty); + debug!(?self_ty); let trait_ref = self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment, false, constness); + debug!(?trait_ref); let item_args = self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args); - debug!("qpath_to_ty: trait_ref={:?}", trait_ref); - Ty::new_projection(tcx, item_def_id, item_args) } @@ -1878,12 +1870,13 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id), } - debug!("path_segs = {:?}", generic_segments); + debug!(?generic_segments); generic_segments } /// Lower a type `Path` to a type. + #[instrument(level = "debug", skip_all)] pub fn lower_path( &self, opt_self_ty: Option>, @@ -1891,13 +1884,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { hir_id: hir::HirId, permit_variants: bool, ) -> Ty<'tcx> { + 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) => { @@ -2176,13 +2165,13 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } /// Lower a type from the HIR to our internal notion of a type. - pub fn lower_ty(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { - self.lower_ty_common(ast_ty, false, false) + pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { + self.lower_ty_common(hir_ty, false, false) } /// Lower a type inside of a path from the HIR to our internal notion of a type. - pub fn lower_ty_in_path(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { - self.lower_ty_common(ast_ty, false, true) + pub fn lower_ty_in_path(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { + self.lower_ty_common(hir_ty, false, true) } fn check_delegation_constraints(&self, sig_id: DefId, span: Span, emit: bool) -> bool { @@ -2302,12 +2291,12 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// 2. `in_path`: Whether the type appears inside of a path. /// Used to provide correct diagnostics for bare trait object types. #[instrument(level = "debug", skip(self), ret)] - fn lower_ty_common(&self, ast_ty: &hir::Ty<'tcx>, borrowed: bool, in_path: bool) -> Ty<'tcx> { + fn lower_ty_common(&self, hir_ty: &hir::Ty<'tcx>, borrowed: bool, in_path: bool) -> Ty<'tcx> { let tcx = self.tcx(); - let result_ty = match &ast_ty.kind { + let result_ty = match &hir_ty.kind { hir::TyKind::InferDelegation(sig_id, idx) => { - self.lower_delegation_ty(*sig_id, *idx, ast_ty.span) + self.lower_delegation_ty(*sig_id, *idx, hir_ty.span) } hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)), hir::TyKind::Ptr(mt) => { @@ -2324,43 +2313,43 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t))) } hir::TyKind::AnonAdt(item_id) => { + let _guard = debug_span!("AnonAdt"); + let did = item_id.owner_id.def_id; let adt_def = tcx.adt_def(did); - let generics = tcx.generics_of(did); - debug!("ast_ty_to_ty_inner(AnonAdt): generics={:?}", generics); let args = ty::GenericArgs::for_item(tcx, did.to_def_id(), |param, _| { tcx.mk_param_from_def(param) }); - debug!("ast_ty_to_ty_inner(AnonAdt): args={:?}", args); + debug!(?args); Ty::new_adt(tcx, adt_def, tcx.mk_args(args)) } 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.lower_fn_ty( - ast_ty.hir_id, + hir_ty.hir_id, bf.unsafety, bf.abi, bf.decl, None, - Some(ast_ty), + 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.lower_trait_object_ty( - ast_ty.span, - ast_ty.hir_id, + hir_ty.span, + hir_ty.hir_id, bounds, lifetime, borrowed, @@ -2370,7 +2359,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => { debug!(?maybe_qself, ?path); let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself)); - self.lower_path(opt_self_ty, path, ast_ty.hir_id, false) + self.lower_path(opt_self_ty, path, hir_ty.hir_id, false) } &hir::TyKind::OpaqueDef(item_id, lifetimes, in_trait) => { let opaque_ty = tcx.hir().item(item_id); @@ -2394,7 +2383,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { hir::TyKind::Path(hir::QPath::TypeRelative(qself, segment)) => { debug!(?qself, ?segment); let ty = self.lower_ty_common(qself, false, true); - self.lower_assoc_path(ast_ty.hir_id, ast_ty.span, ty, qself, segment, false) + self.lower_assoc_path(hir_ty.hir_id, hir_ty.span, ty, qself, segment, false) .map(|(ty, _, _)| ty) .unwrap_or_else(|guar| Ty::new_error(tcx, guar)) } @@ -2426,29 +2415,29 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // values in an ExprKind::Closure, or as // 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 } /// Lower an opaque type (i.e., an existential impl-Trait type) from the HIR. - #[instrument(level = "debug", skip(self), ret)] + #[instrument(level = "debug", skip_all, ret)] fn lower_opaque_ty( &self, def_id: DefId, lifetimes: &[hir::GenericArg<'_>], in_trait: bool, ) -> Ty<'tcx> { - debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes); + debug!(?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 @@ -2474,7 +2463,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { 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) diff --git a/compiler/rustc_hir_analysis/src/astconv/object_safety.rs b/compiler/rustc_hir_analysis/src/astconv/object_safety.rs index 2a3f956bfba99..1490c3f011e8f 100644 --- a/compiler/rustc_hir_analysis/src/astconv/object_safety.rs +++ b/compiler/rustc_hir_analysis/src/astconv/object_safety.rs @@ -19,6 +19,7 @@ use super::HirTyLowerer; impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// Lower a trait object type from the HIR to our internal notion of a type. + #[instrument(level = "debug", skip_all, ret)] pub(super) fn lower_trait_object_ty( &self, span: Span, @@ -157,7 +158,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { 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]).filter_only_self() { - 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() { @@ -244,8 +245,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // 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| { @@ -390,10 +391,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } }) }; - debug!("region_bound: {:?}", region_bound); + debug!(?region_bound); - let ty = Ty::new_dynamic(tcx, existential_predicates, region_bound, representation); - debug!("trait_object_type: {:?}", ty); - ty + Ty::new_dynamic(tcx, existential_predicates, region_bound, representation) } } diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 1fa8cbd96271e..5dcb493b0845b 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -343,8 +343,8 @@ impl<'tcx> ItemCtxt<'tcx> { ItemCtxt { tcx, item_def_id, tainted_by_errors: Cell::new(None) } } - pub fn lower_ty(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { - self.lowerer().lower_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 { @@ -546,9 +546,10 @@ fn get_new_lifetime_name<'tcx>( (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap() } +#[instrument(level = "debug", skip_all)] 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!(item = %it.ident, id = %it.hir_id()); let def_id = item_id.owner_id.def_id; match &it.kind { @@ -1532,19 +1533,19 @@ fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option, def_id: LocalDefId) -> Option, def_id: LocalDefId) -> Option, 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()), @@ -1686,14 +1687,14 @@ fn compute_sig_of_foreign_fn_decl<'tcx>( // Feature gate SIMD types in FFI, since I am not sure that the // ABIs are handled at all correctly. -huonw if abi != abi::Abi::RustIntrinsic && !tcx.features().simd_ffi { - let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| { + let check = |hir_ty: &hir::Ty<'_>, ty: Ty<'_>| { if ty.is_simd() { 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 bc6abc53cadf4..4d6a02f50bfcc 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -218,8 +218,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 { @@ -275,13 +274,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, @@ -302,7 +301,7 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { const TYPE_DEFAULT_NOT_ALLOWED: &'static str = "defaults for type parameters are only allowed in \ `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 2890038a37341..f3eede9604736 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -18,7 +18,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, filter: PredicateFilter, ) -> &'tcx [(ty::Clause<'tcx>, Span)] { @@ -29,9 +29,9 @@ fn associated_type_bounds<'tcx>( ); let icx = ItemCtxt::new(tcx, assoc_item_def_id); - let mut bounds = icx.lowerer().lower_mono_bounds(item_ty, ast_bounds, filter); + let mut bounds = icx.lowerer().lower_mono_bounds(item_ty, hir_bounds, filter); // Associated types are implicitly sized unless a `?Sized` bound is found - icx.lowerer().add_sized_bound(&mut bounds, item_ty, ast_bounds, None, span); + icx.lowerer().add_sized_bound(&mut bounds, item_ty, hir_bounds, None, span); let trait_def_id = tcx.local_parent(assoc_item_def_id); let trait_predicates = tcx.trait_explicit_predicates_and_bounds(trait_def_id); @@ -62,16 +62,16 @@ 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, filter: PredicateFilter, ) -> &'tcx [(ty::Clause<'tcx>, Span)] { ty::print::with_reduced_queries!({ let icx = ItemCtxt::new(tcx, opaque_def_id); - let mut bounds = icx.lowerer().lower_mono_bounds(item_ty, ast_bounds, filter); + let mut bounds = icx.lowerer().lower_mono_bounds(item_ty, hir_bounds, filter); // Opaque types are implicitly sized unless a `?Sized` bound is found - icx.lowerer().add_sized_bound(&mut bounds, item_ty, ast_bounds, None, span); + icx.lowerer().add_sized_bound(&mut bounds, item_ty, hir_bounds, None, span); debug!(?bounds); tcx.arena.alloc_from_iter(bounds.clauses()) diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 6d90a86748623..359aaea8ac0d5 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -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 = node.generics().unwrap_or(NO_GENERICS); + let hir_generics = node.generics().unwrap_or(NO_GENERICS); if let Node::Item(item) = node { match item.kind { ItemKind::Impl(impl_) => { @@ -170,7 +170,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen // Collect the predicates that were written inline by the user on each // 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 { .. } => (), @@ -182,7 +182,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen &mut bounds, param_ty, &[], - Some((param.def_id, ast_generics.predicates)), + Some((param.def_id, hir_generics.predicates)), param.span, ); trace!(?bounds); @@ -205,7 +205,7 @@ 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.lower_ty(bound_pred.bounded_ty); @@ -684,7 +684,7 @@ pub(super) fn type_param_predicates( let item_hir_id = tcx.local_def_id_to_hir_id(item_def_id); let hir_node = tcx.hir_node(item_hir_id); - let Some(ast_generics) = hir_node.generics() else { return result }; + let Some(hir_generics) = hir_node.generics() else { return result }; if let Node::Item(item) = hir_node && let ItemKind::Trait(..) = item.kind // Implied `Self: Trait` and supertrait bounds. @@ -697,7 +697,7 @@ pub(super) fn type_param_predicates( let icx = ItemCtxt::new(tcx, item_def_id); let extra_predicates = extend.into_iter().chain( icx.probe_ty_param_bounds_in_generics( - ast_generics, + hir_generics, def_id, ty, PredicateFilter::SelfThatDefines(assoc_name), @@ -719,17 +719,17 @@ impl<'tcx> ItemCtxt<'tcx> { /// 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, ast_generics))] + #[instrument(level = "trace", skip(self, hir_generics))] fn probe_ty_param_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; }; diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index c5aab115dbf05..c7437cf4f59b9 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -1679,7 +1679,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr: &hir::Expr<'_>, span: Span, variant: &'tcx ty::VariantDef, - ast_fields: &'tcx [hir::ExprField<'tcx>], + hir_fields: &'tcx [hir::ExprField<'tcx>], base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>, ) { let tcx = self.tcx; @@ -1710,7 +1710,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut error_happened = false; // Type-check each field. - for (idx, field) in ast_fields.iter().enumerate() { + for (idx, field) in hir_fields.iter().enumerate() { let ident = tcx.adjust_ident(field.ident, variant.def_id); let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) { seen_fields.insert(ident, field.span); @@ -1739,7 +1739,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { variant, expr, field, - ast_fields, + hir_fields, adt.variant_descr(), ) }; @@ -1754,7 +1754,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.demand_coerce_diag(field.expr, ty, field_type, None, AllowTwoPhase::No); if let Some(diag) = diag { - if idx == ast_fields.len() - 1 { + if idx == hir_fields.len() - 1 { if remaining_fields.is_empty() { self.suggest_fru_from_range_and_emit(field, variant, args, diag); } else { @@ -1768,7 +1768,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Make sure the programmer specified correct number of fields. if adt_kind == AdtKind::Union { - if ast_fields.len() != 1 { + if hir_fields.len() != 1 { struct_span_code_err!( tcx.dcx(), span, @@ -1905,14 +1905,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .collect(); if !private_fields.is_empty() { - self.report_private_fields(adt_ty, span, expr.span, private_fields, ast_fields); + self.report_private_fields(adt_ty, span, expr.span, private_fields, hir_fields); } else { self.report_missing_fields( adt_ty, span, remaining_fields, variant, - ast_fields, + hir_fields, args, ); } @@ -1949,7 +1949,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { span: Span, remaining_fields: UnordMap, variant: &'tcx ty::VariantDef, - ast_fields: &'tcx [hir::ExprField<'tcx>], + hir_fields: &'tcx [hir::ExprField<'tcx>], args: GenericArgsRef<'tcx>, ) { let len = remaining_fields.len(); @@ -1986,8 +1986,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); err.span_label(span, format!("missing {remaining_fields_names}{truncated_fields_error}")); - if let Some(last) = ast_fields.last() { - self.suggest_fru_from_range_and_emit(last, variant, args, err); + if let Some(hir_field) = hir_fields.last() { + self.suggest_fru_from_range_and_emit(hir_field, variant, args, err); } else { err.emit(); } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index b8f1c0e73c0c6..22d391bb6f4ff 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -392,20 +392,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn lower_ty(&self, ast_t: &hir::Ty<'tcx>) -> LoweredTy<'tcx> { - 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) + pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> LoweredTy<'tcx> { + let ty = self.lowerer().lower_ty(hir_ty); + self.register_wf_obligation(ty.into(), hir_ty.span, traits::WellFormed(None)); + LoweredTy::from_raw(self, hir_ty.span, ty) } - pub fn lower_ty_saving_user_provided_ty(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { - let ty = self.lower_ty(ast_ty); - debug!("to_ty_saving_user_provided_ty: ty={:?}", ty); + #[instrument(level = "debug", skip_all)] + pub fn lower_ty_saving_user_provided_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { + let ty = self.lower_ty(hir_ty); + debug!(?ty); if Self::can_contain_user_lifetime_bounds(ty.raw) { let c_ty = self.canonicalize_response(UserType::Ty(ty.raw)); - debug!("to_ty_saving_user_provided_ty: c_ty={:?}", c_ty); - self.typeck_results.borrow_mut().user_provided_types_mut().insert(ast_ty.hir_id, c_ty); + debug!(?c_ty); + self.typeck_results.borrow_mut().user_provided_types_mut().insert(hir_ty.hir_id, c_ty); } ty.normalized @@ -434,16 +435,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn lower_const_arg(&self, ast_c: &hir::AnonConst, param_def_id: DefId) -> ty::Const<'tcx> { - let did = ast_c.def_id; + pub fn lower_const_arg(&self, hir_ct: &hir::AnonConst, param_def_id: DefId) -> ty::Const<'tcx> { + let did = hir_ct.def_id; self.tcx.feed_anon_const_type(did, self.tcx.type_of(param_def_id)); - let c = ty::Const::from_anon_const(self.tcx, did); + let ct = ty::Const::from_anon_const(self.tcx, did); self.register_wf_obligation( - c.into(), - self.tcx.hir().span(ast_c.hir_id), + ct.into(), + self.tcx.hir().span(hir_ct.hir_id), ObligationCauseCode::WellFormed(None), ); - c + ct } // If the type given by the user has free regions, save it for later, since diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index c5bbcc56f86a5..f3615c03215c6 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -3264,8 +3264,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Colon, Nothing, } - let ast_generics = hir.get_generics(id.owner.def_id).unwrap(); - let trait_def_ids: DefIdSet = ast_generics + let hir_generics = hir.get_generics(id.owner.def_id).unwrap(); + let trait_def_ids: DefIdSet = hir_generics .bounds_for_param(def_id) .flat_map(|bp| bp.bounds.iter()) .filter_map(|bound| bound.trait_ref()?.trait_def_id()) @@ -3277,7 +3277,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { "restrict type parameter `{}` with", param.name.ident(), )); - let bounds_span = ast_generics.bounds_span_for_suggestions(def_id); + let bounds_span = hir_generics.bounds_span_for_suggestions(def_id); if rcvr_ty.is_ref() && param.is_impl_trait() && bounds_span.is_some() { err.multipart_suggestions( msg, diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index feca4d384bc38..5efb41f2bd862 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -37,6 +37,7 @@ pub use crate::traits::{MethodViolationCode, ObjectSafetyViolation}; /// Currently that is `Self` in supertraits. This is needed /// because `object_safety_violations` can't be used during /// type collection. +#[instrument(level = "debug", skip(tcx))] pub fn hir_ty_lowering_object_safety_violations( tcx: TyCtxt<'_>, trait_def_id: DefId, @@ -47,9 +48,7 @@ pub fn hir_ty_lowering_object_safety_violations( .filter(|spans| !spans.is_empty()) .map(ObjectSafetyViolation::SupertraitSelf) .collect(); - - debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id, violations); - + debug!(?violations); violations } From 6d5a93949af43b76d84a3c732e2bb1dfae6654f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Sun, 11 Feb 2024 11:09:25 +0100 Subject: [PATCH 4/6] Rename module astconv to hir_ty_lowering Split from the main renaming commit to make git generate a proper diff for ease of reviewing. --- compiler/rustc_hir_analysis/src/collect.rs | 2 +- compiler/rustc_hir_analysis/src/collect/item_bounds.rs | 2 +- compiler/rustc_hir_analysis/src/collect/predicates_of.rs | 2 +- .../src/{astconv => hir_ty_lowering}/bounds.rs | 2 +- .../src/{astconv => hir_ty_lowering}/errors.rs | 2 +- .../src/{astconv => hir_ty_lowering}/generics.rs | 2 +- .../src/{astconv => hir_ty_lowering}/lint.rs | 0 .../src/{astconv => hir_ty_lowering}/mod.rs | 4 ++-- .../src/{astconv => hir_ty_lowering}/object_safety.rs | 2 +- compiler/rustc_hir_analysis/src/lib.rs | 4 ++-- compiler/rustc_hir_typeck/src/closure.rs | 2 +- compiler/rustc_hir_typeck/src/coercion.rs | 2 +- compiler/rustc_hir_typeck/src/expr.rs | 2 +- compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs | 6 ++++-- compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs | 2 +- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 2 +- compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs | 2 +- compiler/rustc_hir_typeck/src/lib.rs | 2 +- compiler/rustc_hir_typeck/src/method/confirm.rs | 6 ++++-- 19 files changed, 26 insertions(+), 22 deletions(-) rename compiler/rustc_hir_analysis/src/{astconv => hir_ty_lowering}/bounds.rs (99%) rename compiler/rustc_hir_analysis/src/{astconv => hir_ty_lowering}/errors.rs (99%) rename compiler/rustc_hir_analysis/src/{astconv => hir_ty_lowering}/generics.rs (99%) rename compiler/rustc_hir_analysis/src/{astconv => hir_ty_lowering}/lint.rs (100%) rename compiler/rustc_hir_analysis/src/{astconv => hir_ty_lowering}/mod.rs (99%) rename compiler/rustc_hir_analysis/src/{astconv => hir_ty_lowering}/object_safety.rs (99%) diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 5dcb493b0845b..404e970403ef6 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -40,9 +40,9 @@ use std::cell::Cell; use std::iter; use std::ops::Bound; -use crate::astconv::HirTyLowerer; use crate::check::intrinsic::intrinsic_operation_unsafety; use crate::errors; +use crate::hir_ty_lowering::HirTyLowerer; pub use type_of::test_opaque_hidden_types; mod generics_of; diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index f3eede9604736..f1b14adcb7a1c 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::{HirTyLowerer, PredicateFilter}; +use crate::hir_ty_lowering::{HirTyLowerer, PredicateFilter}; use rustc_data_structures::fx::FxIndexSet; use rustc_hir as hir; use rustc_infer::traits::util; diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 359aaea8ac0d5..6d8b257a0f5b2 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::{HirTyLowerer, OnlySelfBounds, PredicateFilter}; use crate::bounds::Bounds; use crate::collect::ItemCtxt; use crate::constrained_generic_params as cgp; +use crate::hir_ty_lowering::{HirTyLowerer, OnlySelfBounds, PredicateFilter}; use hir::{HirId, Node}; use rustc_data_structures::fx::FxIndexSet; use rustc_hir as hir; diff --git a/compiler/rustc_hir_analysis/src/astconv/bounds.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs similarity index 99% rename from compiler/rustc_hir_analysis/src/astconv/bounds.rs rename to compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs index 0404fc6ea7f9f..6f7a788ca6eaf 100644 --- a/compiler/rustc_hir_analysis/src/astconv/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -12,9 +12,9 @@ use rustc_trait_selection::traits; use rustc_type_ir::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}; use smallvec::SmallVec; -use crate::astconv::{HirTyLowerer, OnlySelfBounds, PredicateFilter}; use crate::bounds::Bounds; use crate::errors; +use crate::hir_ty_lowering::{HirTyLowerer, OnlySelfBounds, PredicateFilter}; impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// Add a `Sized` bound to the `bounds` if appropriate. diff --git a/compiler/rustc_hir_analysis/src/astconv/errors.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs similarity index 99% rename from compiler/rustc_hir_analysis/src/astconv/errors.rs rename to compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs index bae427a8c84a8..ca2e14ee3591e 100644 --- a/compiler/rustc_hir_analysis/src/astconv/errors.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs @@ -1,9 +1,9 @@ -use crate::astconv::HirTyLowerer; use crate::errors::{ self, AssocTypeBindingNotAllowed, ManualImplementation, MissingTypeParams, ParenthesizedFnTraitExpansion, }; use crate::fluent_generated as fluent; +use crate::hir_ty_lowering::HirTyLowerer; use crate::traits::error_reporting::report_object_safety_error; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::sorted_map::SortedMap; diff --git a/compiler/rustc_hir_analysis/src/astconv/generics.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs similarity index 99% rename from compiler/rustc_hir_analysis/src/astconv/generics.rs rename to compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs index cd980526db160..d340a08ee79b1 100644 --- a/compiler/rustc_hir_analysis/src/astconv/generics.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs @@ -1,5 +1,5 @@ use super::IsMethodCall; -use crate::astconv::{ +use crate::hir_ty_lowering::{ errors::prohibit_assoc_item_binding, ExplicitLateBound, GenericArgCountMismatch, GenericArgCountResult, GenericArgPosition, GenericArgsLowerer, }; diff --git a/compiler/rustc_hir_analysis/src/astconv/lint.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs similarity index 100% rename from compiler/rustc_hir_analysis/src/astconv/lint.rs rename to compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs similarity index 99% rename from compiler/rustc_hir_analysis/src/astconv/mod.rs rename to compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index 8aadbb1f8335d..aef697c658d76 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -19,11 +19,11 @@ pub mod generics; mod lint; mod object_safety; -use crate::astconv::errors::prohibit_assoc_item_binding; -use crate::astconv::generics::{check_generic_arg_count, lower_generic_args}; use crate::bounds::Bounds; use crate::collect::HirPlaceholderCollector; use crate::errors::AmbiguousLifetimeBound; +use crate::hir_ty_lowering::errors::prohibit_assoc_item_binding; +use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args}; use crate::middle::resolve_bound_vars as rbv; use crate::require_c_abi_if_c_variadic; use rustc_ast::TraitObjectSyntax; diff --git a/compiler/rustc_hir_analysis/src/astconv/object_safety.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/object_safety.rs similarity index 99% rename from compiler/rustc_hir_analysis/src/astconv/object_safety.rs rename to compiler/rustc_hir_analysis/src/hir_ty_lowering/object_safety.rs index 1490c3f011e8f..c5a36128cffbe 100644 --- a/compiler/rustc_hir_analysis/src/astconv/object_safety.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/object_safety.rs @@ -1,6 +1,6 @@ -use crate::astconv::{GenericArgCountMismatch, GenericArgCountResult, OnlySelfBounds}; use crate::bounds::Bounds; use crate::errors::TraitObjectDeclaredWithNoTraits; +use crate::hir_ty_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; diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index d7fcb19a536ae..3ec5894700f9f 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -30,7 +30,7 @@ several major phases: The type checker is defined into various submodules which are documented independently: -- astconv: lowers type-system entities from the [HIR][hir] to the +- hir_ty_lowering: lowers type-system entities from the [HIR][hir] to the [`rustc_middle::ty`] representation. - collect: computes the types of each top-level item and enters them into @@ -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 hir_ty_lowering; // FIXME: This module shouldn't be public. pub mod collect; mod constrained_generic_params; diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index 752fe2a4d97ba..40555bf14eb24 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::HirTyLowerer; +use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes}; use rustc_infer::infer::{InferOk, InferResult}; diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index bed0fee6c945c..a218b4ec7a53a 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -41,7 +41,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::HirTyLowerer; +use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::{Coercion, DefineOpaqueTypes, InferOk, InferResult}; use rustc_infer::traits::TraitEngine; diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index c7437cf4f59b9..bd1d7d122d1e3 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -35,8 +35,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::HirTyLowerer as _; use rustc_hir_analysis::check::ty_kind_suggestion; +use rustc_hir_analysis::hir_ty_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 22d391bb6f4ff..8e0be7c7163d9 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -11,8 +11,10 @@ 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::{check_generic_arg_count_for_call, lower_generic_args}; -use rustc_hir_analysis::astconv::{ +use rustc_hir_analysis::hir_ty_lowering::generics::{ + check_generic_arg_count_for_call, lower_generic_args, +}; +use rustc_hir_analysis::hir_ty_lowering::{ ExplicitLateBound, GenericArgCountMismatch, GenericArgCountResult, GenericArgsLowerer, GenericPathSegment, HirTyLowerer, IsMethodCall, }; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index f1c6c8bef0b6e..5695594eb1b8b 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -24,9 +24,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::HirTyLowerer; use rustc_hir_analysis::check::intrinsicck::InlineAsmCtxt; use rustc_hir_analysis::check::potentially_plural_count; +use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_hir_analysis::structured_errors::StructuredDiag; use rustc_index::IndexVec; use rustc_infer::infer::error_reporting::{FailureCode, ObligationCauseExt}; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index ed70c63ccdcdf..a83a1169c98b9 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -12,7 +12,7 @@ use hir::def_id::CRATE_DEF_ID; use rustc_errors::{DiagCtxt, ErrorGuaranteed}; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_hir_analysis::astconv::HirTyLowerer; +use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_infer::infer; use rustc_infer::infer::error_reporting::sub_relations::SubRelations; use rustc_infer::infer::error_reporting::TypeErrCtxt; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index a7763e91b7a47..21f52f7208092 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::HirTyLowerer; +use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_infer::traits::{self}; use rustc_middle::lint::in_external_macro; use rustc_middle::middle::stability::EvalResult; diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 0cba6f538f0f7..0b67b37df29d8 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -57,8 +57,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::HirTyLowerer; use rustc_hir_analysis::check::check_abi; +use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::traits::{ObligationCauseCode, ObligationInspector, WellFormedLoc}; use rustc_middle::query::Providers; diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 361d38baf323a..d5413a120c734 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -4,8 +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::{check_generic_arg_count_for_call, lower_generic_args}; -use rustc_hir_analysis::astconv::{GenericArgsLowerer, HirTyLowerer, IsMethodCall}; +use rustc_hir_analysis::hir_ty_lowering::generics::{ + check_generic_arg_count_for_call, lower_generic_args, +}; +use rustc_hir_analysis::hir_ty_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}; From 72472c831c56c208a8a174846c66dad0fa27e0e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Fri, 22 Mar 2024 05:47:11 +0100 Subject: [PATCH 5/6] Arrange methods on HirTyLowerer more logically MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This makes it easier to read the trait definition for newcomers: Sorted from least “complex” to most “complex” followed by trivial “plumbing” and grouped by area. * Move `allow_infer` above all `*_infer` methods * It's the least complex method of those * Allows the `*_infer` to be placed right next to each other * Move `probe_ty_param_bounds` further down right next to `lower_assoc_ty` and `probe_adt` * It's more complex than the `infer` methods, it should come “later” * Now all required lowering functions are grouped together * Move the “plumbing” function `set_tainted_by_errors` further down below any actual lowering methods. * Provided method should come last --- compiler/rustc_hir_analysis/src/collect.rs | 30 ++++----- .../src/hir_ty_lowering/mod.rs | 48 +++++++------- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 66 +++++++++---------- 3 files changed, 72 insertions(+), 72 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 404e970403ef6..a705d3bc1073f 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -372,23 +372,14 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> { self.item_def_id.to_def_id() } - fn probe_ty_param_bounds( - &self, - span: Span, - def_id: LocalDefId, - assoc_name: Ident, - ) -> ty::GenericPredicates<'tcx> { - self.tcx.at(span).type_param_predicates((self.item_def_id, def_id, assoc_name)) + fn allow_infer(&self) -> bool { + false } fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option> { None } - fn allow_infer(&self) -> bool { - false - } - fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> { Ty::new_error_with_message(self.tcx(), span, "bad placeholder type") } @@ -403,6 +394,15 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> { ty::Const::new_error_with_message(self.tcx(), ty, span, "bad placeholder constant") } + fn probe_ty_param_bounds( + &self, + span: Span, + def_id: LocalDefId, + assoc_name: Ident, + ) -> ty::GenericPredicates<'tcx> { + self.tcx.at(span).type_param_predicates((self.item_def_id, def_id, assoc_name)) + } + fn lower_assoc_ty( &self, span: Span, @@ -496,10 +496,6 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> { ty.ty_adt_def() } - fn set_tainted_by_errors(&self, err: ErrorGuaranteed) { - self.tainted_by_errors.set(Some(err)); - } - fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) { // There's no place to record types from signatures? } @@ -507,6 +503,10 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> { fn infcx(&self) -> Option<&InferCtxt<'tcx>> { None } + + fn set_tainted_by_errors(&self, err: ErrorGuaranteed) { + self.tainted_by_errors.set(Some(err)); + } } /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present. diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index aef697c658d76..109e00d4f24e5 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -89,6 +89,24 @@ pub trait HirTyLowerer<'tcx> { /// Returns the [`DefId`] of the overarching item whose constituents get lowered. fn item_def_id(&self) -> DefId; + /// Returns `true` if the current context allows the use of inference variables. + fn allow_infer(&self) -> bool; + + /// Returns the region to use when a lifetime is omitted (and not elided). + fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) + -> Option>; + + /// Returns the type to use when a type is omitted. + fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>; + + /// Returns the const to use when a const is omitted. + fn ct_infer( + &self, + ty: Ty<'tcx>, + param: Option<&ty::GenericParamDef>, + span: Span, + ) -> Const<'tcx>; + /// Probe bounds in scope where the bounded type coincides with the given type parameter. /// /// Rephrased, this returns bounds of the form `T: Trait`, where `T` is a type parameter @@ -110,24 +128,6 @@ pub trait HirTyLowerer<'tcx> { assoc_name: Ident, ) -> ty::GenericPredicates<'tcx>; - /// Returns the region to use when a lifetime is omitted (and not elided). - fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) - -> Option>; - - /// Returns the type to use when a type is omitted. - fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>; - - /// Returns `true` if the current context allows the use of inference variables. - fn allow_infer(&self) -> bool; - - /// Returns the const to use when a const is omitted. - fn ct_infer( - &self, - ty: Ty<'tcx>, - param: Option<&ty::GenericParamDef>, - span: Span, - ) -> Const<'tcx>; - /// Lower an associated type to a projection. /// /// This method has to be defined by the concrete lowering context because @@ -156,15 +156,18 @@ pub trait HirTyLowerer<'tcx> { /// or to an enum variant depending on the result of this function. fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option>; + /// Record the lowered type of a HIR node in this context. + fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span); + + /// The inference context of the lowering context if applicable. + fn infcx(&self) -> Option<&InferCtxt<'tcx>>; + /// Taint the context with errors. /// /// Invoke this when you encounter an error from some prior pass like name resolution. /// This is used to help suppress derived errors typeck might otherwise report. fn set_tainted_by_errors(&self, e: ErrorGuaranteed); - /// Record the lowered type of a HIR node in this context. - fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span); - /// Convenience method for coercing the lowering context into a trait object type. /// /// Most lowering routines are defined on the trait object type directly @@ -175,9 +178,6 @@ pub trait HirTyLowerer<'tcx> { { self } - - /// The inference context of the lowering context if applicable. - fn infcx(&self) -> Option<&InferCtxt<'tcx>>; } /// New-typed boolean indicating whether explicit late-bound lifetimes diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index a83a1169c98b9..efa2862177e16 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -221,31 +221,8 @@ impl<'a, 'tcx> HirTyLowerer<'tcx> for FnCtxt<'a, 'tcx> { self.body_id.to_def_id() } - fn probe_ty_param_bounds( - &self, - _: Span, - def_id: LocalDefId, - _: Ident, - ) -> ty::GenericPredicates<'tcx> { - let tcx = self.tcx; - let item_def_id = tcx.hir().ty_param_owner(def_id); - let generics = tcx.generics_of(item_def_id); - let index = generics.param_def_id_to_index[&def_id.to_def_id()]; - // HACK(eddyb) should get the original `Span`. - let span = tcx.def_span(def_id); - ty::GenericPredicates { - parent: None, - predicates: tcx.arena.alloc_from_iter( - self.param_env.caller_bounds().iter().filter_map(|predicate| { - match predicate.kind().skip_binder() { - ty::ClauseKind::Trait(data) if data.self_ty().is_param(index) => { - Some((predicate, span)) - } - _ => None, - } - }), - ), - } + fn allow_infer(&self) -> bool { + true } fn re_infer(&self, def: Option<&ty::GenericParamDef>, span: Span) -> Option> { @@ -256,10 +233,6 @@ impl<'a, 'tcx> HirTyLowerer<'tcx> for FnCtxt<'a, 'tcx> { Some(self.next_region_var(v)) } - fn allow_infer(&self) -> bool { - true - } - fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> { match param { Some(param) => self.var_for_def(span, param).as_type().unwrap(), @@ -292,6 +265,33 @@ impl<'a, 'tcx> HirTyLowerer<'tcx> for FnCtxt<'a, 'tcx> { } } + fn probe_ty_param_bounds( + &self, + _: Span, + def_id: LocalDefId, + _: Ident, + ) -> ty::GenericPredicates<'tcx> { + let tcx = self.tcx; + let item_def_id = tcx.hir().ty_param_owner(def_id); + let generics = tcx.generics_of(item_def_id); + let index = generics.param_def_id_to_index[&def_id.to_def_id()]; + // HACK(eddyb) should get the original `Span`. + let span = tcx.def_span(def_id); + ty::GenericPredicates { + parent: None, + predicates: tcx.arena.alloc_from_iter( + self.param_env.caller_bounds().iter().filter_map(|predicate| { + match predicate.kind().skip_binder() { + ty::ClauseKind::Trait(data) if data.self_ty().is_param(index) => { + Some((predicate, span)) + } + _ => None, + } + }), + ), + } + } + fn lower_assoc_ty( &self, span: Span, @@ -328,10 +328,6 @@ impl<'a, 'tcx> HirTyLowerer<'tcx> for FnCtxt<'a, 'tcx> { } } - fn set_tainted_by_errors(&self, e: ErrorGuaranteed) { - self.infcx.set_tainted_by_errors(e) - } - fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span) { // FIXME: normalization and escaping regions let ty = if !ty.has_escaping_bound_vars() { @@ -355,6 +351,10 @@ impl<'a, 'tcx> HirTyLowerer<'tcx> for FnCtxt<'a, 'tcx> { fn infcx(&self) -> Option<&infer::InferCtxt<'tcx>> { Some(&self.infcx) } + + fn set_tainted_by_errors(&self, e: ErrorGuaranteed) { + self.infcx.set_tainted_by_errors(e) + } } /// The `ty` representation of a user-provided type. Depending on the use-site From 5e73a8b2f149a359abb2717d5fa91f63add75eef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Thu, 14 Mar 2024 15:07:34 +0100 Subject: [PATCH 6/6] Notify fmease on changes to HIR ty lowering --- triagebot.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/triagebot.toml b/triagebot.toml index 0a36eab7b8738..4e163a3bb1c0b 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -499,6 +499,10 @@ of `ObligationCtxt`. """ cc = ["@lcnr", "@compiler-errors"] +[mentions."compiler/rustc_hir_analysis/src/hir_ty_lowering"] +message = "HIR ty lowering was modified" +cc = ["@fmease"] + [mentions."compiler/rustc_error_codes/src/lib.rs"] message = "Some changes occurred in diagnostic error codes" cc = ["@GuillaumeGomez"]