diff --git a/Cargo.lock b/Cargo.lock index 34fc0860a4b75..ad8fada320d61 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3354,7 +3354,6 @@ version = "0.0.0" dependencies = [ "rustc_abi", "rustc_ast", - "rustc_ast_pretty", "rustc_attr_data_structures", "rustc_attr_parsing", "rustc_data_structures", diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 491a9bbda79b1..8ae5f5fad2061 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -4054,6 +4054,17 @@ impl TryFrom for ForeignItemKind { pub type ForeignItem = Item; +#[derive(Debug)] +pub enum AstOwner { + NonOwner, + Synthetic(rustc_span::def_id::LocalDefId), + Crate(P), + Item(P), + TraitItem(P), + ImplItem(P), + ForeignItem(P), +} + // Some nodes are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { diff --git a/compiler/rustc_ast/src/mut_visit.rs b/compiler/rustc_ast/src/mut_visit.rs index 3eae19f4daa11..f9c018da90992 100644 --- a/compiler/rustc_ast/src/mut_visit.rs +++ b/compiler/rustc_ast/src/mut_visit.rs @@ -142,7 +142,10 @@ pub fn walk_flat_map_stmt( stmts } -fn walk_flat_map_stmt_kind(vis: &mut T, kind: StmtKind) -> SmallVec<[StmtKind; 1]> { +pub fn walk_flat_map_stmt_kind( + vis: &mut T, + kind: StmtKind, +) -> SmallVec<[StmtKind; 1]> { match kind { StmtKind::Let(mut local) => smallvec![StmtKind::Let({ vis.visit_local(&mut local); diff --git a/compiler/rustc_ast_lowering/Cargo.toml b/compiler/rustc_ast_lowering/Cargo.toml index dc571f5c3671a..6e23549047f1f 100644 --- a/compiler/rustc_ast_lowering/Cargo.toml +++ b/compiler/rustc_ast_lowering/Cargo.toml @@ -10,7 +10,6 @@ doctest = false # tidy-alphabetical-start rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } -rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_attr_parsing = { path = "../rustc_attr_parsing" } rustc_data_structures = { path = "../rustc_data_structures" } diff --git a/compiler/rustc_ast_lowering/src/asm.rs b/compiler/rustc_ast_lowering/src/asm.rs index af279e07acc6e..c65860ddd1360 100644 --- a/compiler/rustc_ast_lowering/src/asm.rs +++ b/compiler/rustc_ast_lowering/src/asm.rs @@ -20,10 +20,10 @@ use super::errors::{ }; use crate::{ AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, ParamMode, - ResolverAstLoweringExt, fluent_generated as fluent, + fluent_generated as fluent, }; -impl<'a, 'hir> LoweringContext<'a, 'hir> { +impl<'hir> LoweringContext<'hir> { pub(crate) fn lower_inline_asm( &mut self, sp: Span, @@ -200,7 +200,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }, InlineAsmOperand::Sym { sym } => { let static_def_id = self - .resolver .get_partial_res(sym.id) .and_then(|res| res.full_res()) .and_then(|res| match res { diff --git a/compiler/rustc_ast_lowering/src/block.rs b/compiler/rustc_ast_lowering/src/block.rs index c3222b79e55c9..3bc05b22a408b 100644 --- a/compiler/rustc_ast_lowering/src/block.rs +++ b/compiler/rustc_ast_lowering/src/block.rs @@ -5,7 +5,7 @@ use smallvec::SmallVec; use crate::{ImplTraitContext, ImplTraitPosition, LoweringContext}; -impl<'a, 'hir> LoweringContext<'a, 'hir> { +impl<'hir> LoweringContext<'hir> { pub(super) fn lower_block( &mut self, b: &Block, @@ -43,17 +43,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { stmts.push(hir::Stmt { hir_id, kind, span }); } StmtKind::Item(it) => { - stmts.extend(self.lower_item_ref(it).into_iter().enumerate().map( - |(i, item_id)| { - let hir_id = match i { - 0 => self.lower_node_id(s.id), - _ => self.next_id(), - }; - let kind = hir::StmtKind::Item(item_id); - let span = self.lower_span(s.span); - hir::Stmt { hir_id, kind, span } - }, - )); + let item_id = self.lower_item_ref(it); + let hir_id = self.lower_node_id(s.id); + let kind = hir::StmtKind::Item(item_id); + let span = self.lower_span(s.span); + stmts.push(hir::Stmt { hir_id, kind, span }); } StmtKind::Expr(e) => { let e = self.lower_expr(e); diff --git a/compiler/rustc_ast_lowering/src/delegation.rs b/compiler/rustc_ast_lowering/src/delegation.rs index 42d25b512f5c9..575c2ff4b38a6 100644 --- a/compiler/rustc_ast_lowering/src/delegation.rs +++ b/compiler/rustc_ast_lowering/src/delegation.rs @@ -46,12 +46,15 @@ use rustc_ast::*; use rustc_errors::ErrorGuaranteed; use rustc_hir::def_id::DefId; use rustc_middle::span_bug; -use rustc_middle::ty::{Asyncness, ResolverAstLowering}; +use rustc_middle::ty::Asyncness; +use rustc_span::symbol::kw; use rustc_span::{Ident, Span, Symbol}; use {rustc_ast as ast, rustc_hir as hir}; -use super::{GenericArgsMode, ImplTraitContext, LoweringContext, ParamMode}; -use crate::{AllowReturnTypeNotation, ImplTraitPosition, ResolverAstLoweringExt}; +use super::{ + AllowReturnTypeNotation, GenericArgsMode, ImplTraitContext, ImplTraitPosition, LoweringContext, + ParamMode, +}; pub(crate) struct DelegationResults<'hir> { pub body_id: hir::BodyId, @@ -60,22 +63,7 @@ pub(crate) struct DelegationResults<'hir> { pub generics: &'hir hir::Generics<'hir>, } -impl<'hir> LoweringContext<'_, 'hir> { - /// Defines whether the delegatee is an associated function whose first parameter is `self`. - pub(crate) fn delegatee_is_method( - &self, - item_id: NodeId, - path_id: NodeId, - span: Span, - is_in_trait_impl: bool, - ) -> bool { - let sig_id = self.get_delegation_sig_id(item_id, path_id, span, is_in_trait_impl); - let Ok(sig_id) = sig_id else { - return false; - }; - self.is_method(sig_id, span) - } - +impl<'hir> LoweringContext<'hir> { fn is_method(&self, def_id: DefId, span: Span) -> bool { match self.tcx.def_kind(def_id) { DefKind::Fn => false, @@ -101,10 +89,11 @@ impl<'hir> LoweringContext<'_, 'hir> { let sig_id = self.get_delegation_sig_id(item_id, delegation.id, span, is_in_trait_impl); match sig_id { Ok(sig_id) => { + let is_method = self.is_method(sig_id, span); let (param_count, c_variadic) = self.param_count(sig_id); let decl = self.lower_delegation_decl(sig_id, param_count, c_variadic, span); let sig = self.lower_delegation_sig(sig_id, decl, span); - let body_id = self.lower_delegation_body(delegation, param_count, span); + let body_id = self.lower_delegation_body(delegation, is_method, param_count, span); let ident = self.lower_ident(delegation.ident); let generics = self.lower_delegation_generics(span); DelegationResults { body_id, sig, ident, generics } @@ -125,8 +114,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } fn get_resolution_id(&self, node_id: NodeId, span: Span) -> Result { - let def_id = - self.resolver.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id()); + let def_id = self.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id()); def_id.ok_or_else(|| { self.tcx.dcx().span_delayed_bug( span, @@ -234,10 +222,21 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::FnSig { decl, header, span } } - fn generate_param(&mut self, idx: usize, span: Span) -> (hir::Param<'hir>, NodeId) { + fn generate_param( + &mut self, + is_method: bool, + idx: usize, + span: Span, + ) -> (hir::Param<'hir>, NodeId) { let pat_node_id = self.next_node_id(); let pat_id = self.lower_node_id(pat_node_id); - let ident = Ident::with_dummy_span(Symbol::intern(&format!("arg{idx}"))); + // FIXME(cjgillot) AssocItem currently relies on self parameter being exactly named `self`. + let name = if is_method && idx == 0 { + kw::SelfLower + } else { + Symbol::intern(&format!("arg{idx}")) + }; + let ident = Ident::with_dummy_span(name); let pat = self.arena.alloc(hir::Pat { hir_id: pat_id, kind: hir::PatKind::Binding(hir::BindingMode::NONE, pat_id, ident, None), @@ -248,9 +247,21 @@ impl<'hir> LoweringContext<'_, 'hir> { (hir::Param { hir_id: self.next_id(), pat, ty_span: span, span }, pat_node_id) } - fn generate_arg(&mut self, idx: usize, param_id: HirId, span: Span) -> hir::Expr<'hir> { + fn generate_arg( + &mut self, + is_method: bool, + idx: usize, + param_id: HirId, + span: Span, + ) -> hir::Expr<'hir> { + // FIXME(cjgillot) AssocItem currently relies on self parameter being exactly named `self`. + let name = if is_method && idx == 0 { + kw::SelfLower + } else { + Symbol::intern(&format!("arg{idx}")) + }; let segments = self.arena.alloc_from_iter(iter::once(hir::PathSegment { - ident: Ident::with_dummy_span(Symbol::intern(&format!("arg{idx}"))), + ident: Ident::with_dummy_span(name), hir_id: self.next_id(), res: Res::Local(param_id), args: None, @@ -264,6 +275,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_delegation_body( &mut self, delegation: &Delegation, + is_method: bool, param_count: usize, span: Span, ) -> BodyId { @@ -274,14 +286,14 @@ impl<'hir> LoweringContext<'_, 'hir> { let mut args: Vec> = Vec::with_capacity(param_count); for idx in 0..param_count { - let (param, pat_node_id) = this.generate_param(idx, span); + let (param, pat_node_id) = this.generate_param(is_method, idx, span); parameters.push(param); let arg = if let Some(block) = block && idx == 0 { let mut self_resolver = SelfResolver { - resolver: this.resolver, + ctxt: this, path_id: delegation.id, self_param_id: pat_node_id, }; @@ -290,7 +302,7 @@ impl<'hir> LoweringContext<'_, 'hir> { this.ident_and_label_to_local_id.insert(pat_node_id, param.pat.hir_id.local_id); this.lower_target_expr(&block) } else { - this.generate_arg(idx, param.pat.hir_id, span) + this.generate_arg(is_method, idx, param.pat.hir_id, span) }; args.push(arg); } @@ -427,25 +439,25 @@ impl<'hir> LoweringContext<'_, 'hir> { } } -struct SelfResolver<'a> { - resolver: &'a mut ResolverAstLowering, +struct SelfResolver<'r, 'hir> { + ctxt: &'r mut LoweringContext<'hir>, path_id: NodeId, self_param_id: NodeId, } -impl<'a> SelfResolver<'a> { +impl SelfResolver<'_, '_> { fn try_replace_id(&mut self, id: NodeId) { - if let Some(res) = self.resolver.partial_res_map.get(&id) + if let Some(res) = self.ctxt.get_partial_res(id) && let Some(Res::Local(sig_id)) = res.full_res() && sig_id == self.path_id { let new_res = PartialRes::new(Res::Local(self.self_param_id)); - self.resolver.partial_res_map.insert(id, new_res); + self.ctxt.partial_res_overrides.insert(id, new_res); } } } -impl<'ast, 'a> Visitor<'ast> for SelfResolver<'a> { +impl<'ast> Visitor<'ast> for SelfResolver<'_, '_> { fn visit_id(&mut self, id: NodeId) { self.try_replace_id(id); } diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 8747e624a4a9e..58a1192bbb853 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -3,12 +3,12 @@ use std::sync::Arc; use rustc_ast::ptr::P as AstP; use rustc_ast::*; -use rustc_ast_pretty::pprust::expr_to_string; use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir as hir; use rustc_hir::HirId; use rustc_hir::def::{DefKind, Res}; +use rustc_hir::definitions::DefPathData; use rustc_middle::span_bug; use rustc_middle::ty::TyCtxt; use rustc_session::errors::report_lit_error; @@ -52,7 +52,7 @@ impl<'v> rustc_ast::visit::Visitor<'v> for WillCreateDefIdsVisitor { } } -impl<'hir> LoweringContext<'_, 'hir> { +impl<'hir> LoweringContext<'hir> { fn lower_exprs(&mut self, exprs: &[AstP]) -> &'hir [hir::Expr<'hir>] { self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x))) } @@ -462,13 +462,16 @@ impl<'hir> LoweringContext<'_, 'hir> { let mut invalid_expr_error = |tcx: TyCtxt<'_>, span| { // Avoid emitting the error multiple times. if error.is_none() { + let sm = tcx.sess.source_map(); let mut const_args = vec![]; let mut other_args = vec![]; for (idx, arg) in args.iter().enumerate() { - if legacy_args_idx.contains(&idx) { - const_args.push(format!("{{ {} }}", expr_to_string(arg))); - } else { - other_args.push(expr_to_string(arg)); + if let Ok(arg) = sm.span_to_snippet(arg.span) { + if legacy_args_idx.contains(&idx) { + const_args.push(format!("{{ {} }}", arg)); + } else { + other_args.push(arg); + } } } let suggestion = UseConstGenericArg { @@ -488,7 +491,13 @@ impl<'hir> LoweringContext<'_, 'hir> { for (idx, arg) in args.iter().cloned().enumerate() { if legacy_args_idx.contains(&idx) { let node_id = self.next_node_id(); - self.create_def(node_id, None, DefKind::AnonConst, f.span); + self.create_def( + node_id, + None, + DefKind::AnonConst, + DefPathData::LateAnonConst, + f.span, + ); let mut visitor = WillCreateDefIdsVisitor {}; let const_value = if let ControlFlow::Break(span) = visitor.visit_expr(&arg) { AstP(Expr { @@ -1260,7 +1269,7 @@ impl<'hir> LoweringContext<'_, 'hir> { whole_span: Span, ) -> hir::ExprKind<'hir> { // Return early in case of an ordinary assignment. - fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool { + fn is_ordinary(lower_ctx: &mut LoweringContext<'_>, lhs: &Expr) -> bool { match &lhs.kind { ExprKind::Array(..) | ExprKind::Struct(..) @@ -1320,7 +1329,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ) -> Option<(&'a Option>, &'a Path)> { if let ExprKind::Path(qself, path) = &expr.kind { // Does the path resolve to something disallowed in a tuple struct/variant pattern? - if let Some(partial_res) = self.resolver.get_partial_res(expr.id) { + if let Some(partial_res) = self.get_partial_res(expr.id) { if let Some(res) = partial_res.full_res() && !res.expected_in_tuple_struct_pat() { @@ -1342,7 +1351,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ) -> Option<(&'a Option>, &'a Path)> { if let ExprKind::Path(qself, path) = &expr.kind { // Does the path resolve to something disallowed in a unit struct/variant pattern? - if let Some(partial_res) = self.resolver.get_partial_res(expr.id) { + if let Some(partial_res) = self.get_partial_res(expr.id) { if let Some(res) = partial_res.full_res() && !res.expected_in_unit_struct_pat() { diff --git a/compiler/rustc_ast_lowering/src/format.rs b/compiler/rustc_ast_lowering/src/format.rs index 943cde90dd20b..716a356b3954d 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -8,7 +8,7 @@ use rustc_span::{DesugaringKind, Ident, Span, Symbol, sym}; use super::LoweringContext; -impl<'hir> LoweringContext<'_, 'hir> { +impl<'hir> LoweringContext<'hir> { pub(crate) fn lower_format_args(&mut self, sp: Span, fmt: &FormatArgs) -> hir::ExprKind<'hir> { // Never call the const constructor of `fmt::Arguments` if the // format_args!() had any arguments _before_ flattening/inlining. @@ -236,7 +236,7 @@ enum ArgumentType { /// ::new_…(arg) /// ``` fn make_argument<'hir>( - ctx: &mut LoweringContext<'_, 'hir>, + ctx: &mut LoweringContext<'hir>, sp: Span, arg: &'hir hir::Expr<'hir>, ty: ArgumentType, @@ -285,7 +285,7 @@ fn make_argument<'hir>( /// ::Implied /// ``` fn make_count<'hir>( - ctx: &mut LoweringContext<'_, 'hir>, + ctx: &mut LoweringContext<'hir>, sp: Span, count: &Option, argmap: &mut FxIndexMap<(usize, ArgumentType), Option>, @@ -336,7 +336,7 @@ fn make_count<'hir>( /// } /// ``` fn make_format_spec<'hir>( - ctx: &mut LoweringContext<'_, 'hir>, + ctx: &mut LoweringContext<'hir>, sp: Span, placeholder: &FormatPlaceholder, argmap: &mut FxIndexMap<(usize, ArgumentType), Option>, @@ -397,7 +397,7 @@ fn make_format_spec<'hir>( } fn expand_format_args<'hir>( - ctx: &mut LoweringContext<'_, 'hir>, + ctx: &mut LoweringContext<'hir>, macsp: Span, fmt: &FormatArgs, allow_const: bool, diff --git a/compiler/rustc_ast_lowering/src/index.rs b/compiler/rustc_ast_lowering/src/index.rs index 956cb580d1032..1ef64f5a3526b 100644 --- a/compiler/rustc_ast_lowering/src/index.rs +++ b/compiler/rustc_ast_lowering/src/index.rs @@ -381,28 +381,16 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { }) } - fn visit_trait_item_ref(&mut self, ii: &'hir TraitItemRef) { - // Do not visit the duplicate information in TraitItemRef. We want to - // map the actual nodes, not the duplicate ones in the *Ref. - let TraitItemRef { id, ident: _, kind: _, span: _ } = *ii; - - self.visit_nested_trait_item(id); + fn visit_trait_item_ref(&mut self, id: &'hir TraitItemId) { + self.visit_nested_trait_item(*id); } - fn visit_impl_item_ref(&mut self, ii: &'hir ImplItemRef) { - // Do not visit the duplicate information in ImplItemRef. We want to - // map the actual nodes, not the duplicate ones in the *Ref. - let ImplItemRef { id, ident: _, kind: _, span: _, trait_item_def_id: _ } = *ii; - - self.visit_nested_impl_item(id); + fn visit_impl_item_ref(&mut self, id: &'hir ImplItemId) { + self.visit_nested_impl_item(*id); } - fn visit_foreign_item_ref(&mut self, fi: &'hir ForeignItemRef) { - // Do not visit the duplicate information in ForeignItemRef. We want to - // map the actual nodes, not the duplicate ones in the *Ref. - let ForeignItemRef { id, ident: _, span: _ } = *fi; - - self.visit_nested_foreign_item(id); + fn visit_foreign_item_ref(&mut self, id: &'hir ForeignItemId) { + self.visit_nested_foreign_item(*id); } fn visit_where_predicate(&mut self, predicate: &'hir WherePredicate<'hir>) { diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index bdcb750ba260a..caa6f24a6abdf 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1,18 +1,16 @@ use rustc_abi::ExternAbi; use rustc_ast::ptr::P; -use rustc_ast::visit::AssocCtxt; use rustc_ast::*; use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_errors::{E0570, ErrorGuaranteed, struct_span_code_err}; use rustc_hir::def::{DefKind, PerNS, Res}; -use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId}; +use rustc_hir::def_id::CRATE_DEF_ID; use rustc_hir::{self as hir, HirId, LifetimeSource, PredicateOrigin}; -use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::span_bug; use rustc_middle::ty::{ResolverAstLowering, TyCtxt}; use rustc_span::edit_distance::find_best_match_for_name; -use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, kw, sym}; -use smallvec::{SmallVec, smallvec}; +use rustc_span::{DesugaringKind, Ident, Span, Symbol, kw, sym}; +use smallvec::SmallVec; use thin_vec::ThinVec; use tracing::instrument; @@ -22,15 +20,14 @@ use super::errors::{ }; use super::stability::{enabled_names, gate_unstable_abi}; use super::{ - AstOwner, FnDeclKind, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode, + FnDeclKind, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode, ResolverAstLoweringExt, }; -pub(super) struct ItemLowerer<'a, 'hir> { +pub(super) struct ItemLowerer<'hir> { pub(super) tcx: TyCtxt<'hir>, - pub(super) resolver: &'a mut ResolverAstLowering, - pub(super) ast_index: &'a IndexSlice>, - pub(super) owners: &'a mut IndexVec>, + pub(super) resolver: &'hir ResolverAstLowering, + pub(super) next_node_id: NodeId, } /// When we have a ty alias we *may* have two where clauses. To give the best diagnostics, we set the span @@ -54,55 +51,51 @@ fn add_ty_alias_where_clause( generics.where_clause.span = where_clause.span; } -impl<'a, 'hir> ItemLowerer<'a, 'hir> { +impl<'hir> ItemLowerer<'hir> { fn with_lctx( &mut self, owner: NodeId, - f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>, - ) { - let mut lctx = LoweringContext::new(self.tcx, self.resolver); - lctx.with_hir_id_owner(owner, |lctx| f(lctx)); - - for (def_id, info) in lctx.children { - let owner = self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom); - assert!( - matches!(owner, hir::MaybeOwner::Phantom), - "duplicate copy of {def_id:?} in lctx.children" - ); - *owner = info; - } + f: impl FnOnce(&mut LoweringContext<'hir>) -> hir::OwnerNode<'hir>, + ) -> hir::MaybeOwner<'hir> { + let mut lctx = LoweringContext::new(self.tcx, self.resolver, owner, self.next_node_id); + + let item = f(&mut lctx); + debug_assert_eq!(lctx.current_hir_id_owner, item.def_id()); + + let info = lctx.make_owner_info(item); + + hir::MaybeOwner::Owner(lctx.arena.alloc(info)) } - pub(super) fn lower_node(&mut self, def_id: LocalDefId) { - let owner = self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom); - if let hir::MaybeOwner::Phantom = owner { - let node = self.ast_index[def_id]; - match node { - AstOwner::NonOwner => {} - AstOwner::Crate(c) => { - assert_eq!(self.resolver.node_id_to_def_id[&CRATE_NODE_ID], CRATE_DEF_ID); - self.with_lctx(CRATE_NODE_ID, |lctx| { - let module = lctx.lower_mod(&c.items, &c.spans); - // FIXME(jdonszelman): is dummy span ever a problem here? - lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs, DUMMY_SP); - hir::OwnerNode::Crate(module) - }) - } - AstOwner::Item(item) => { - self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item))) - } - AstOwner::AssocItem(item, ctxt) => { - self.with_lctx(item.id, |lctx| lctx.lower_assoc_item(item, ctxt)) - } - AstOwner::ForeignItem(item) => self.with_lctx(item.id, |lctx| { - hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item)) - }), - } - } + #[instrument(level = "debug", skip(self, c))] + pub(super) fn lower_crate(&mut self, c: &Crate) -> hir::MaybeOwner<'hir> { + debug_assert_eq!(self.resolver.node_id_to_def_id[&CRATE_NODE_ID], CRATE_DEF_ID); + self.with_lctx(CRATE_NODE_ID, |lctx| { + let module = lctx.lower_mod(&c.items, &c.spans); + lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs, c.spans.inner_span); + hir::OwnerNode::Crate(module) + }) + } + + #[instrument(level = "debug", skip(self))] + pub(super) fn lower_item(&mut self, item: &Item) -> hir::MaybeOwner<'hir> { + self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item))) + } + + pub(super) fn lower_trait_item(&mut self, item: &AssocItem) -> hir::MaybeOwner<'hir> { + self.with_lctx(item.id, |lctx| hir::OwnerNode::TraitItem(lctx.lower_trait_item(item))) + } + + pub(super) fn lower_impl_item(&mut self, item: &AssocItem) -> hir::MaybeOwner<'hir> { + self.with_lctx(item.id, |lctx| hir::OwnerNode::ImplItem(lctx.lower_impl_item(item))) + } + + pub(super) fn lower_foreign_item(&mut self, item: &ForeignItem) -> hir::MaybeOwner<'hir> { + self.with_lctx(item.id, |lctx| hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item))) } } -impl<'hir> LoweringContext<'_, 'hir> { +impl<'hir> LoweringContext<'hir> { pub(super) fn lower_mod( &mut self, items: &[P], @@ -113,37 +106,22 @@ impl<'hir> LoweringContext<'_, 'hir> { inner_span: self.lower_span(spans.inner_span), inject_use_span: self.lower_span(spans.inject_use_span), }, - item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_ref(x))), + item_ids: self.arena.alloc_from_iter(items.iter().map(|x| self.lower_item_ref(x))), }) } - pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> { - let mut node_ids = smallvec![hir::ItemId { owner_id: self.owner_id(i.id) }]; - if let ItemKind::Use(use_tree) = &i.kind { - self.lower_item_id_use_tree(use_tree, &mut node_ids); - } - node_ids - } - - fn lower_item_id_use_tree(&mut self, tree: &UseTree, vec: &mut SmallVec<[hir::ItemId; 1]>) { - match &tree.kind { - UseTreeKind::Nested { items, .. } => { - for &(ref nested, id) in items { - vec.push(hir::ItemId { owner_id: self.owner_id(id) }); - self.lower_item_id_use_tree(nested, vec); - } - } - UseTreeKind::Simple(..) | UseTreeKind::Glob => {} - } + pub(super) fn lower_item_ref(&mut self, i: &Item) -> hir::ItemId { + hir::ItemId { owner_id: self.owner_id(i.id) } } fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> { + let owner_id = self.current_hir_id_owner; + let hir_id: HirId = owner_id.into(); let vis_span = self.lower_span(i.vis.span); - let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id); let attrs = self.lower_attrs(hir_id, &i.attrs, i.span); let kind = self.lower_item_kind(i.span, i.id, hir_id, attrs, vis_span, &i.kind); let item = hir::Item { - owner_id: hir_id.expect_owner(), + owner_id, kind, vis_span, span: self.lower_span(i.span), @@ -393,11 +371,9 @@ impl<'hir> LoweringContext<'_, 'hir> { (trait_ref, lowered_ty) }); - let new_impl_items = self.arena.alloc_from_iter( - impl_items - .iter() - .map(|item| self.lower_impl_item_ref(item, trait_ref.is_some())), - ); + let new_impl_items = self + .arena + .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item))); // `defaultness.has_value()` is never called for an `impl`, always `true` in order // to not cause an assertion failure inside the `lower_defaultness` function. @@ -628,21 +604,9 @@ impl<'hir> LoweringContext<'_, 'hir> { } } - fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) -> hir::OwnerNode<'hir> { - // Evaluate with the lifetimes in `params` in-scope. - // This is used to track which lifetimes have already been defined, - // and which need to be replicated when lowering an async fn. - match ctxt { - AssocCtxt::Trait => hir::OwnerNode::TraitItem(self.lower_trait_item(item)), - AssocCtxt::Impl { of_trait } => { - hir::OwnerNode::ImplItem(self.lower_impl_item(item, of_trait)) - } - } - } - fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> { - let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id); - let owner_id = hir_id.expect_owner(); + let owner_id = self.current_hir_id_owner; + let hir_id: HirId = owner_id.into(); let attrs = self.lower_attrs(hir_id, &i.attrs, i.span); let (ident, kind) = match &i.kind { ForeignItemKind::Fn(box Fn { sig, ident, generics, define_opaque, .. }) => { @@ -706,14 +670,8 @@ impl<'hir> LoweringContext<'_, 'hir> { self.arena.alloc(item) } - fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef { - hir::ForeignItemRef { - id: hir::ForeignItemId { owner_id: self.owner_id(i.id) }, - // `unwrap` is safe because `ForeignItemKind::MacCall` is the only foreign item kind - // without an identifier and it cannot reach here. - ident: self.lower_ident(i.kind.ident().unwrap()), - span: self.lower_span(i.span), - } + fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemId { + hir::ForeignItemId { owner_id: self.owner_id(i.id) } } fn lower_variant(&mut self, item_kind: &ItemKind, v: &Variant) -> hir::Variant<'hir> { @@ -819,9 +777,9 @@ impl<'hir> LoweringContext<'_, 'hir> { } fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> { - let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id); + let trait_item_def_id = self.current_hir_id_owner; + let hir_id: HirId = trait_item_def_id.into(); let attrs = self.lower_attrs(hir_id, &i.attrs, i.span); - let trait_item_def_id = hir_id.expect_owner(); let (ident, generics, kind, has_default) = match &i.kind { AssocItemKind::Const(box ConstItem { @@ -972,32 +930,8 @@ impl<'hir> LoweringContext<'_, 'hir> { self.arena.alloc(item) } - fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef { - let (ident, kind) = match &i.kind { - AssocItemKind::Const(box ConstItem { ident, .. }) => { - (*ident, hir::AssocItemKind::Const) - } - AssocItemKind::Type(box TyAlias { ident, .. }) => (*ident, hir::AssocItemKind::Type), - AssocItemKind::Fn(box Fn { ident, sig, .. }) => { - (*ident, hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }) - } - AssocItemKind::Delegation(box delegation) => ( - delegation.ident, - hir::AssocItemKind::Fn { - has_self: self.delegatee_is_method(i.id, delegation.id, i.span, false), - }, - ), - AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => { - panic!("macros should have been expanded by now") - } - }; - let id = hir::TraitItemId { owner_id: self.owner_id(i.id) }; - hir::TraitItemRef { - id, - ident: self.lower_ident(ident), - span: self.lower_span(i.span), - kind, - } + fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemId { + hir::TraitItemId { owner_id: self.owner_id(i.id) } } /// Construct `ExprKind::Err` for the given `span`. @@ -1005,15 +939,16 @@ impl<'hir> LoweringContext<'_, 'hir> { self.expr(span, hir::ExprKind::Err(guar)) } - fn lower_impl_item( - &mut self, - i: &AssocItem, - is_in_trait_impl: bool, - ) -> &'hir hir::ImplItem<'hir> { + fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> { + let owner_id = self.current_hir_id_owner; + let hir_id: HirId = owner_id.into(); + let parent_id = self.tcx.local_parent(owner_id.def_id); + let is_in_trait_impl = + matches!(self.tcx.def_kind(parent_id), DefKind::Impl { of_trait: true }); + // Since `default impl` is not yet implemented, this is always true in impls. let has_value = true; let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value); - let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id); let attrs = self.lower_attrs(hir_id, &i.attrs, i.span); let (ident, (generics, kind)) = match &i.kind { @@ -1120,7 +1055,7 @@ impl<'hir> LoweringContext<'_, 'hir> { }; let item = hir::ImplItem { - owner_id: hir_id.expect_owner(), + owner_id, ident: self.lower_ident(ident), generics, kind, @@ -1128,41 +1063,16 @@ impl<'hir> LoweringContext<'_, 'hir> { span: self.lower_span(i.span), defaultness, has_delayed_lints: !self.delayed_lints.is_empty(), - }; - self.arena.alloc(item) - } - - fn lower_impl_item_ref(&mut self, i: &AssocItem, is_in_trait_impl: bool) -> hir::ImplItemRef { - hir::ImplItemRef { - id: hir::ImplItemId { owner_id: self.owner_id(i.id) }, - // `unwrap` is safe because `AssocItemKind::{MacCall,DelegationMac}` are the only - // assoc item kinds without an identifier and they cannot reach here. - ident: self.lower_ident(i.kind.ident().unwrap()), - span: self.lower_span(i.span), - kind: match &i.kind { - AssocItemKind::Const(..) => hir::AssocItemKind::Const, - AssocItemKind::Type(..) => hir::AssocItemKind::Type, - AssocItemKind::Fn(box Fn { sig, .. }) => { - hir::AssocItemKind::Fn { has_self: sig.decl.has_self() } - } - AssocItemKind::Delegation(box delegation) => hir::AssocItemKind::Fn { - has_self: self.delegatee_is_method( - i.id, - delegation.id, - i.span, - is_in_trait_impl, - ), - }, - AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => { - panic!("macros should have been expanded by now") - } - }, trait_item_def_id: self - .resolver .get_partial_res(i.id) .map(|r| r.expect_full_res().opt_def_id()) .unwrap_or(None), - } + }; + self.arena.alloc(item) + } + + fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemId { + hir::ImplItemId { owner_id: self.owner_id(i.id) } } fn lower_defaultness( @@ -1396,7 +1306,7 @@ impl<'hir> LoweringContext<'_, 'hir> { pub(crate) fn lower_coroutine_body_with_moved_arguments( &mut self, decl: &FnDecl, - lower_body: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::Expr<'hir>, + lower_body: impl FnOnce(&mut LoweringContext<'hir>) -> hir::Expr<'hir>, fn_decl_span: Span, body_span: Span, coroutine_kind: CoroutineKind, @@ -1533,7 +1443,7 @@ impl<'hir> LoweringContext<'_, 'hir> { parameters.push(new_parameter); } - let mkbody = |this: &mut LoweringContext<'_, 'hir>| { + let mkbody = |this: &mut LoweringContext<'hir>| { // Create a block from the user's function body: let user_body = lower_body(this); @@ -1735,11 +1645,7 @@ impl<'hir> LoweringContext<'_, 'hir> { }; let compute_is_param = || { // Check if the where clause type is a plain type parameter. - match self - .resolver - .get_partial_res(bound_pred.bounded_ty.id) - .and_then(|r| r.full_res()) - { + match self.get_partial_res(bound_pred.bounded_ty.id).and_then(|r| r.full_res()) { Some(Res::Def(DefKind::TyParam, def_id)) if bound_pred.bound_generic_params.is_empty() => { @@ -1806,7 +1712,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // Introduce extra lifetimes if late resolution tells us to. let extra_lifetimes = self.resolver.extra_lifetime_params(parent_node_id); - params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| { + params.extend(extra_lifetimes.into_iter().filter_map(|&(ident, node_id, res)| { self.lifetime_res_to_generic_param( ident, node_id, @@ -1848,7 +1754,7 @@ impl<'hir> LoweringContext<'_, 'hir> { return; }; let define_opaque = define_opaque.iter().filter_map(|(id, path)| { - let res = self.resolver.get_partial_res(*id); + let res = self.get_partial_res(*id); let Some(did) = res.and_then(|res| res.expect_full_res().opt_def_id()) else { self.dcx().span_delayed_bug(path.span, "should have errored in resolve"); return None; diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 0706bdb119f01..c363ad58d195b 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -40,30 +40,33 @@ use std::sync::Arc; +use rustc_ast::mut_visit::{self, MutVisitor}; use rustc_ast::node_id::NodeMap; +use rustc_ast::ptr::P; use rustc_ast::{self as ast, *}; use rustc_attr_parsing::{AttributeParser, OmitDoc}; -use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; -use rustc_data_structures::sync::spawn; +use rustc_data_structures::steal::Steal; use rustc_data_structures::tagged_ptr::TaggedRef; +use rustc_data_structures::unord::ExtendUnord; use rustc_errors::{DiagArgFromDisplay, DiagCtxtHandle}; use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res}; -use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId}; +use rustc_hir::def_id::{LOCAL_CRATE, LocalDefId, LocalDefIdMap}; +use rustc_hir::definitions::{DefPathData, DisambiguatorState}; use rustc_hir::lints::DelayedLint; use rustc_hir::{ self as hir, AngleBrackets, ConstArg, GenericArg, HirId, ItemLocalMap, LangItem, LifetimeSource, LifetimeSyntax, ParamName, TraitCandidate, }; -use rustc_index::{Idx, IndexSlice, IndexVec}; +use rustc_index::{Idx, IndexVec}; use rustc_macros::extension; use rustc_middle::span_bug; use rustc_middle::ty::{ResolverAstLowering, TyCtxt}; use rustc_session::parse::add_feature_diagnostics; use rustc_span::symbol::{Ident, Symbol, kw, sym}; use rustc_span::{DUMMY_SP, DesugaringKind, Span}; -use smallvec::SmallVec; +use smallvec::{SmallVec, smallvec}; use thin_vec::ThinVec; use tracing::{debug, instrument, trace}; @@ -89,9 +92,10 @@ pub mod stability; rustc_fluent_macro::fluent_messages! { "../messages.ftl" } -struct LoweringContext<'a, 'hir> { +struct LoweringContext<'hir> { tcx: TyCtxt<'hir>, - resolver: &'a mut ResolverAstLowering, + resolver: &'hir ResolverAstLowering, + disambiguator: DisambiguatorState, /// Used to allocate HIR nodes. arena: &'hir hir::Arena<'hir>, @@ -103,7 +107,7 @@ struct LoweringContext<'a, 'hir> { /// Attributes inside the owner being lowered. attrs: SortedMap, /// Collect items that were created by lowering the current owner. - children: Vec<(LocalDefId, hir::MaybeOwner<'hir>)>, + children: LocalDefIdMap>, contract_ensures: Option<(Span, Ident, HirId)>, @@ -124,7 +128,7 @@ struct LoweringContext<'a, 'hir> { current_hir_id_owner: hir::OwnerId, item_local_id_counter: hir::ItemLocalId, - trait_map: ItemLocalMap>, + trait_map: ItemLocalMap<&'hir [TraitCandidate]>, impl_trait_defs: Vec>, impl_trait_bounds: Vec>, @@ -134,6 +138,14 @@ struct LoweringContext<'a, 'hir> { /// NodeIds that are lowered inside the current HIR owner. Only used for duplicate lowering check. #[cfg(debug_assertions)] node_id_to_local_id: NodeMap, + /// The `NodeId` space is split in two. + /// `0..resolver.next_node_id` are created by the resolver on the AST. + /// The higher part `resolver.next_node_id..next_node_id` are created during lowering. + next_node_id: NodeId, + /// Maps the `NodeId`s created during lowering to `LocalDefId`s. + node_id_to_def_id: NodeMap, + /// Overlay over resolver's `partial_res_map` used by delegation. + partial_res_overrides: NodeMap, allow_try_trait: Arc<[Symbol]>, allow_gen_future: Arc<[Symbol]>, @@ -147,27 +159,37 @@ struct LoweringContext<'a, 'hir> { attribute_parser: AttributeParser<'hir>, } -impl<'a, 'hir> LoweringContext<'a, 'hir> { - fn new(tcx: TyCtxt<'hir>, resolver: &'a mut ResolverAstLowering) -> Self { +impl<'hir> LoweringContext<'hir> { + fn new( + tcx: TyCtxt<'hir>, + resolver: &'hir ResolverAstLowering, + owner: NodeId, + next_node_id: NodeId, + ) -> Self { let registered_tools = tcx.registered_tools(()).iter().map(|x| x.name).collect(); + let current_hir_id_owner = hir::OwnerId { def_id: resolver.node_id_to_def_id[&owner] }; Self { // Pseudo-globals. tcx, resolver, + disambiguator: DisambiguatorState::new(), arena: tcx.hir_arena, // HirId handling. bodies: Vec::new(), define_opaque: None, attrs: SortedMap::default(), - children: Vec::default(), + children: LocalDefIdMap::default(), contract_ensures: None, - current_hir_id_owner: hir::CRATE_OWNER_ID, - item_local_id_counter: hir::ItemLocalId::ZERO, + current_hir_id_owner, + item_local_id_counter: hir::ItemLocalId::new(1), ident_and_label_to_local_id: Default::default(), #[cfg(debug_assertions)] - node_id_to_local_id: Default::default(), + node_id_to_local_id: [(owner, hir::ItemLocalId::ZERO)].into_iter().collect(), trait_map: Default::default(), + next_node_id, + node_id_to_def_id: NodeMap::default(), + partial_res_overrides: NodeMap::default(), // Lowering state. catch_scope: None, @@ -245,10 +267,6 @@ impl ResolverAstLowering { None } - fn get_partial_res(&self, id: NodeId) -> Option { - self.partial_res_map.get(&id).copied() - } - /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`. fn get_import_res(&self, id: NodeId) -> PerNS>> { self.import_res_map.get(&id).copied().unwrap_or_default() @@ -271,8 +289,8 @@ impl ResolverAstLowering { /// /// The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring /// should appear at the enclosing `PolyTraitRef`. - fn extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> { - self.extra_lifetime_params_map.get(&id).cloned().unwrap_or_default() + fn extra_lifetime_params(&self, id: NodeId) -> &[(Ident, NodeId, LifetimeRes)] { + self.extra_lifetime_params_map.get(&id).map_or(&[], |v| &v[..]) } } @@ -372,119 +390,200 @@ enum FnDeclKind { Impl, } -#[derive(Copy, Clone)] -enum AstOwner<'a> { - NonOwner, - Crate(&'a ast::Crate), - Item(&'a ast::Item), - AssocItem(&'a ast::AssocItem, visit::AssocCtxt), - ForeignItem(&'a ast::ForeignItem), -} +pub fn index_ast<'tcx>( + tcx: TyCtxt<'tcx>, + (): (), +) -> (IndexVec>, NodeId) { + // Queries that borrow `resolver_for_lowering`. + tcx.ensure_done().output_filenames(()); + tcx.ensure_done().early_lint_checks(()); + tcx.ensure_done().get_lang_items(()); + tcx.ensure_done().debugger_visualizers(LOCAL_CRATE); + + let (resolver, krate) = tcx.resolver_for_lowering(); + let mut krate = krate.steal(); + + let mut indexer = Indexer { + node_id_to_def_id: &resolver.node_id_to_def_id, + index: IndexVec::new(), + next_node_id: resolver.next_node_id, + }; + indexer.visit_crate(&mut krate); + indexer.insert(CRATE_NODE_ID, AstOwner::Crate(P(krate))); + return (indexer.index, indexer.next_node_id); -fn index_crate<'a>( - node_id_to_def_id: &NodeMap, - krate: &'a Crate, -) -> IndexVec> { - let mut indexer = Indexer { node_id_to_def_id, index: IndexVec::new() }; - *indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner) = - AstOwner::Crate(krate); - visit::walk_crate(&mut indexer, krate); - return indexer.index; - - struct Indexer<'s, 'a> { + struct Indexer<'s> { node_id_to_def_id: &'s NodeMap, - index: IndexVec>, + index: IndexVec>, + next_node_id: NodeId, } - impl<'a> visit::Visitor<'a> for Indexer<'_, 'a> { - fn visit_attribute(&mut self, _: &'a Attribute) { + impl Indexer<'_> { + fn insert(&mut self, id: NodeId, node: AstOwner) { + let def_id = self.node_id_to_def_id[&id]; + self.index.ensure_contains_elem(def_id, || Steal::new(AstOwner::NonOwner)); + self.index[def_id] = Steal::new(node); + } + + fn make_dummy( + &mut self, + id: NodeId, + span: Span, + dummy: impl FnOnce(P) -> K, + ) -> P> { + use rustc_ast::token::Delimiter; + use rustc_ast::tokenstream::{DelimSpan, TokenStream}; + use thin_vec::thin_vec; + + P(Item { + attrs: AttrVec::default(), + id, + span, + vis: Visibility { kind: VisibilityKind::Public, span, tokens: None }, + // Lacking a better choice, we replace the contents with a macro call. + // Unexpanded macros should never reach lowering, so this is not confusing. + kind: dummy(P(MacCall { + path: Path { span, segments: thin_vec![], tokens: None }, + args: P(DelimArgs { + dspan: DelimSpan::from_single(span), + delim: Delimiter::Parenthesis, + tokens: TokenStream::new(Vec::new()), + }), + })), + tokens: None, + }) + } + + fn replace_with_dummy( + &mut self, + item: &mut ast::Item, + dummy: impl FnOnce(P) -> K, + node: impl FnOnce(P>) -> AstOwner, + ) { + let dummy = self.make_dummy(item.id, item.span, dummy); + let item = std::mem::replace(item, *dummy); + self.insert(item.id, node(P(item))); + } + + #[tracing::instrument(level = "trace", skip(self))] + fn visit_item_id_use_tree( + &mut self, + tree: &UseTree, + parent: LocalDefId, + items: &mut SmallVec<[P; 1]>, + ) { + match tree.kind { + UseTreeKind::Glob | UseTreeKind::Simple(_) => {} + UseTreeKind::Nested { items: ref nested_vec, span } => { + for &(ref nested, id) in nested_vec { + self.insert(id, AstOwner::Synthetic(parent)); + items.push(self.make_dummy(id, span, ItemKind::MacCall)); + + let def_id = self.node_id_to_def_id[&id]; + self.visit_item_id_use_tree(nested, def_id, items); + } + } + } + } + } + + impl MutVisitor for Indexer<'_> { + fn visit_attribute(&mut self, _: &mut Attribute) { // We do not want to lower expressions that appear in attributes, // as they are not accessible to the rest of the HIR. } - fn visit_item(&mut self, item: &'a ast::Item) { + fn flat_map_item(&mut self, mut item: P) -> SmallVec<[P; 1]> { let def_id = self.node_id_to_def_id[&item.id]; - *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) = AstOwner::Item(item); - visit::walk_item(self, item) + mut_visit::walk_item(self, &mut *item); + let dummy = self.make_dummy(item.id, item.span, ItemKind::MacCall); + let mut items = smallvec![dummy]; + if let ItemKind::Use(ref use_tree) = item.kind { + self.visit_item_id_use_tree(use_tree, def_id, &mut items); + } + self.insert(item.id, AstOwner::Item(item)); + items } - fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) { - let def_id = self.node_id_to_def_id[&item.id]; - *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) = - AstOwner::AssocItem(item, ctxt); - visit::walk_assoc_item(self, item, ctxt); + fn flat_map_stmt(&mut self, stmt: Stmt) -> SmallVec<[Stmt; 1]> { + let Stmt { id, span, kind } = stmt; + let mut id = Some(id); + mut_visit::walk_flat_map_stmt_kind(self, kind) + .into_iter() + .map(|kind| { + let id = id.take().unwrap_or_else(|| { + let next = self.next_node_id; + self.next_node_id.increment_by(1); + next + }); + Stmt { id, kind, span } + }) + .collect() } - fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) { - let def_id = self.node_id_to_def_id[&item.id]; - *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) = - AstOwner::ForeignItem(item); - visit::walk_item(self, item); + fn visit_assoc_item(&mut self, item: &mut AssocItem, ctxt: visit::AssocCtxt) { + mut_visit::walk_assoc_item(self, item, ctxt); + match ctxt { + visit::AssocCtxt::Trait => { + self.replace_with_dummy(item, AssocItemKind::MacCall, AstOwner::TraitItem) + } + visit::AssocCtxt::Impl { .. } => { + self.replace_with_dummy(item, AssocItemKind::MacCall, AstOwner::ImplItem) + } + } } - } -} - -/// Compute the hash for the HIR of the full crate. -/// This hash will then be part of the crate_hash which is stored in the metadata. -fn compute_hir_hash( - tcx: TyCtxt<'_>, - owners: &IndexSlice>, -) -> Fingerprint { - let mut hir_body_nodes: Vec<_> = owners - .iter_enumerated() - .filter_map(|(def_id, info)| { - let info = info.as_owner()?; - let def_path_hash = tcx.hir_def_path_hash(def_id); - Some((def_path_hash, info)) - }) - .collect(); - hir_body_nodes.sort_unstable_by_key(|bn| bn.0); - tcx.with_stable_hashing_context(|mut hcx| { - let mut stable_hasher = StableHasher::new(); - hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher); - stable_hasher.finish() - }) + fn visit_foreign_item(&mut self, item: &mut ForeignItem) { + mut_visit::walk_item(self, item); + self.replace_with_dummy(item, ForeignItemKind::MacCall, AstOwner::ForeignItem); + } + } } -pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> hir::Crate<'_> { - let sess = tcx.sess; +#[instrument(level = "trace", skip(tcx))] +pub fn lower_to_hir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> hir::MaybeOwner<'_> { // Queries that borrow `resolver_for_lowering`. tcx.ensure_done().output_filenames(()); tcx.ensure_done().early_lint_checks(()); tcx.ensure_done().debugger_visualizers(LOCAL_CRATE); tcx.ensure_done().get_lang_items(()); - let (mut resolver, krate) = tcx.resolver_for_lowering().steal(); - - let ast_index = index_crate(&resolver.node_id_to_def_id, &krate); - let mut owners = IndexVec::from_fn_n( - |_| hir::MaybeOwner::Phantom, - tcx.definitions_untracked().def_index_count(), - ); - - let mut lowerer = item::ItemLowerer { - tcx, - resolver: &mut resolver, - ast_index: &ast_index, - owners: &mut owners, + let (resolver, _) = tcx.resolver_for_lowering(); + let (ast_index, next_node_id) = tcx.index_ast(()); + let node = ast_index.get(def_id).map(Steal::steal); + + let mut item_lowerer = item::ItemLowerer { tcx, resolver, next_node_id: *next_node_id }; + + // The item existed in the AST. + let parent_id = match node.as_ref() { + Some(AstOwner::Crate(c)) => return item_lowerer.lower_crate(&c), + Some(AstOwner::Item(item)) => return item_lowerer.lower_item(&item), + Some(AstOwner::TraitItem(item)) => { + return item_lowerer.lower_trait_item(&item); + } + Some(AstOwner::ImplItem(item)) => { + return item_lowerer.lower_impl_item(&item); + } + Some(AstOwner::ForeignItem(item)) => return item_lowerer.lower_foreign_item(&item), + Some(AstOwner::Synthetic(parent_id)) => *parent_id, + Some(AstOwner::NonOwner) | None => tcx.local_parent(def_id), }; - for def_id in ast_index.indices() { - lowerer.lower_node(def_id); - } - drop(ast_index); + tcx.sess.time("drop_ast", || std::mem::drop(node)); - // Drop AST to free memory. It can be expensive so try to drop it on a separate thread. - let prof = sess.prof.clone(); - spawn(move || { - let _timer = prof.verbose_generic_activity("drop_ast"); - drop(krate); - }); + // The item did not exist in the AST, it was created by its parent. + let mut parent_info = tcx.lower_to_hir(parent_id); + if let hir::MaybeOwner::NonOwner(hir_id) = parent_info { + parent_info = tcx.lower_to_hir(hir_id.owner); + } - // Don't hash unless necessary, because it's expensive. - let opt_hir_hash = - if tcx.needs_crate_hash() { Some(compute_hir_hash(tcx, &owners)) } else { None }; - hir::Crate { owners, opt_hir_hash } + let parent_info = parent_info.unwrap(); + *parent_info.children.get(&def_id).unwrap_or_else(|| { + panic!( + "{:?} does not appear in children of {:?}", + def_id, + parent_info.nodes.node().def_id() + ) + }) } #[derive(Copy, Clone, PartialEq, Debug)] @@ -514,12 +613,13 @@ enum GenericArgsMode { Silence, } -impl<'a, 'hir> LoweringContext<'a, 'hir> { +impl<'hir> LoweringContext<'hir> { fn create_def( &mut self, node_id: ast::NodeId, name: Option, def_kind: DefKind, + def_path_data: DefPathData, span: Span, ) -> LocalDefId { let parent = self.current_hir_id_owner.def_id; @@ -535,32 +635,43 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let def_id = self .tcx .at(span) - .create_def(parent, name, def_kind, None, &mut self.resolver.disambiguator) + .create_def(parent, name, def_kind, Some(def_path_data), &mut self.disambiguator) .def_id(); debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id); - self.resolver.node_id_to_def_id.insert(node_id, def_id); + self.node_id_to_def_id.insert(node_id, def_id); def_id } fn next_node_id(&mut self) -> NodeId { - let start = self.resolver.next_node_id; + let start = self.next_node_id; let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds"); - self.resolver.next_node_id = ast::NodeId::from_u32(next); + self.next_node_id = ast::NodeId::from_u32(next); start } /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name /// resolver (if any). + #[instrument(level = "trace", skip(self), ret)] fn opt_local_def_id(&self, node: NodeId) -> Option { - self.resolver.node_id_to_def_id.get(&node).copied() + self.node_id_to_def_id + .get(&node) + .or_else(|| self.resolver.node_id_to_def_id.get(&node)) + .copied() } fn local_def_id(&self, node: NodeId) -> LocalDefId { self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`")) } + fn get_partial_res(&self, id: NodeId) -> Option { + self.partial_res_overrides + .get(&id) + .or_else(|| self.resolver.partial_res_map.get(&id)) + .copied() + } + /// Given the id of an owner node in the AST, returns the corresponding `OwnerId`. fn owner_id(&self, node: NodeId) -> hir::OwnerId { hir::OwnerId { def_id: self.local_def_id(node) } @@ -594,6 +705,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let current_impl_trait_defs = std::mem::take(&mut self.impl_trait_defs); let current_impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds); let current_delayed_lints = std::mem::take(&mut self.delayed_lints); + let current_children = std::mem::take(&mut self.children); // Do not reset `next_node_id` and `node_id_to_def_id`: // we want `f` to be able to refer to the `LocalDefId`s that the caller created. @@ -628,9 +740,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.impl_trait_defs = current_impl_trait_defs; self.impl_trait_bounds = current_impl_trait_bounds; self.delayed_lints = current_delayed_lints; + self.children = current_children; + self.children.extend_unord(info.children.items().map(|(&def_id, &info)| (def_id, info))); - debug_assert!(!self.children.iter().any(|(id, _)| id == &owner_id.def_id)); - self.children.push((owner_id.def_id, hir::MaybeOwner::Owner(info))); + debug_assert!(!self.children.contains_key(&owner_id.def_id)); + self.children.insert(owner_id.def_id, hir::MaybeOwner::Owner(info)); } fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> { @@ -639,6 +753,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let define_opaque = std::mem::take(&mut self.define_opaque); let trait_map = std::mem::take(&mut self.trait_map); let delayed_lints = std::mem::take(&mut self.delayed_lints).into_boxed_slice(); + let children = std::mem::take(&mut self.children); #[cfg(debug_assertions)] for (id, attrs) in attrs.iter() { @@ -652,16 +767,39 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let bodies = SortedMap::from_presorted_elements(bodies); // Don't hash unless necessary, because it's expensive. - let (opt_hash_including_bodies, attrs_hash, delayed_lints_hash) = + let (bodies_hash, attrs_hash, delayed_lints_hash) = self.tcx.hash_owner_nodes(node, &bodies, &attrs, &delayed_lints, define_opaque); let num_nodes = self.item_local_id_counter.as_usize(); let (nodes, parenting) = index::index_hir(self.tcx, node, &bodies, num_nodes); - let nodes = hir::OwnerNodes { opt_hash_including_bodies, nodes, bodies }; + let nodes = hir::OwnerNodes { opt_hash: bodies_hash, nodes, bodies }; let attrs = hir::AttributeMap { map: attrs, opt_hash: attrs_hash, define_opaque }; let delayed_lints = hir::lints::DelayedLints { lints: delayed_lints, opt_hash: delayed_lints_hash }; - self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map, delayed_lints }) + let opt_hash = if self.tcx.needs_crate_hash() { + Some(self.tcx.with_stable_hashing_context(|mut hcx| { + let mut stable_hasher = StableHasher::new(); + nodes.hash_stable(&mut hcx, &mut stable_hasher); + parenting.hash_stable(&mut hcx, &mut stable_hasher); + attrs.hash_stable(&mut hcx, &mut stable_hasher); + trait_map.hash_stable(&mut hcx, &mut stable_hasher); + delayed_lints.hash_stable(&mut hcx, &mut stable_hasher); + children.hash_stable(&mut hcx, &mut stable_hasher); + stable_hasher.finish() + })) + } else { + None + }; + + self.arena.alloc(hir::OwnerInfo { + opt_hash, + nodes, + parenting, + attrs, + trait_map, + delayed_lints, + children, + }) } /// This method allocates a new `HirId` for the given `NodeId`. @@ -680,11 +818,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let hir_id = HirId { owner, local_id }; if let Some(def_id) = self.opt_local_def_id(ast_node_id) { - self.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id))); + self.children.insert(def_id, hir::MaybeOwner::NonOwner(hir_id)); } - if let Some(traits) = self.resolver.trait_map.remove(&ast_node_id) { - self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice()); + if let Some(traits) = self.resolver.trait_map.get(&ast_node_id) { + self.trait_map.insert(hir_id.local_id, &traits[..]); } // Check whether the same `NodeId` is lowered more than once. @@ -725,7 +863,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } fn expect_full_res(&mut self, id: NodeId) -> Res { - self.resolver.get_partial_res(id).map_or(Res::Err, |pr| pr.expect_full_res()) + self.get_partial_res(id).map_or(Res::Err, |pr| pr.expect_full_res()) } fn lower_import_res(&mut self, id: NodeId, span: Span) -> PerNS> { @@ -820,6 +958,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { param, Some(kw::UnderscoreLifetime), DefKind::LifetimeParam, + DefPathData::DesugaredAnonymousLifetime, ident.span, ); debug!(?_def_id); @@ -863,7 +1002,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { .collect(); let extra_lifetimes = self.resolver.extra_lifetime_params(binder); debug!(?extra_lifetimes); - generic_params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| { + generic_params.extend(extra_lifetimes.iter().filter_map(|&(ident, node_id, res)| { self.lifetime_res_to_generic_param(ident, node_id, res, hir::GenericParamSource::Binder) })); let generic_params = self.arena.alloc_from_iter(generic_params); @@ -1152,7 +1291,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // FIXME: Should we be handling `(PATH_TO_CONST)`? TyKind::Path(None, path) => { if let Some(res) = self - .resolver .get_partial_res(ty.id) .and_then(|partial_res| partial_res.full_res()) { @@ -1199,7 +1337,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // The other cases when a qpath should be opportunistically made a trait object are handled // by `ty_path`. if qself.is_none() - && let Some(partial_res) = self.resolver.get_partial_res(t.id) + && let Some(partial_res) = self.get_partial_res(t.id) && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res() { let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| { @@ -1540,7 +1678,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let [segment] = path.segments.as_slice() else { panic!(); }; - let res = self.resolver.get_partial_res(*id).map_or(Res::Err, |partial_res| { + let res = self.get_partial_res(*id).map_or(Res::Err, |partial_res| { partial_res.full_res().expect("no partial res expected for precise capture arg") }); hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg { @@ -2155,7 +2293,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // We're lowering a const argument that was originally thought to be a type argument, // so the def collector didn't create the def ahead of time. That's why we have to do // it here. - let def_id = self.create_def(node_id, None, DefKind::AnonConst, span); + let def_id = self.create_def( + node_id, + None, + DefKind::AnonConst, + DefPathData::LateAnonConst, + span, + ); let hir_id = self.lower_node_id(node_id); let path_expr = Expr { @@ -2201,7 +2345,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { &anon.value }; let maybe_res = - self.resolver.get_partial_res(expr.id).and_then(|partial_res| partial_res.full_res()); + self.get_partial_res(expr.id).and_then(|partial_res| partial_res.full_res()); if let ExprKind::Path(qself, path) = &expr.kind && path.is_potential_trivial_const_arg(tcx.features().min_generic_const_args()) && (tcx.features().min_generic_const_args() @@ -2495,7 +2639,7 @@ impl<'hir> GenericArgsCtor<'hir> { && self.parenthesized == hir::GenericArgsParentheses::No } - fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> { + fn into_generic_args(self, this: &LoweringContext<'hir>) -> &'hir hir::GenericArgs<'hir> { let ga = hir::GenericArgs { args: this.arena.alloc_from_iter(self.args), constraints: self.constraints, diff --git a/compiler/rustc_ast_lowering/src/pat.rs b/compiler/rustc_ast_lowering/src/pat.rs index e444062104813..7b0ab6df232e7 100644 --- a/compiler/rustc_ast_lowering/src/pat.rs +++ b/compiler/rustc_ast_lowering/src/pat.rs @@ -4,6 +4,7 @@ use rustc_ast::ptr::P; use rustc_ast::*; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir::def::{DefKind, Res}; +use rustc_hir::definitions::DefPathData; use rustc_hir::{self as hir, LangItem}; use rustc_middle::span_bug; use rustc_span::source_map::{Spanned, respan}; @@ -12,10 +13,11 @@ use rustc_span::{DesugaringKind, Ident, Span}; use super::errors::{ ArbitraryExpressionInPattern, ExtraDoubleDot, MisplacedDoubleDot, SubTupleBinding, }; -use super::{ImplTraitContext, LoweringContext, ParamMode, ResolverAstLoweringExt}; -use crate::{AllowReturnTypeNotation, ImplTraitPosition}; +use super::{ + AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode, +}; -impl<'a, 'hir> LoweringContext<'a, 'hir> { +impl<'hir> LoweringContext<'hir> { pub(crate) fn lower_pat(&mut self, pattern: &Pat) -> &'hir hir::Pat<'hir> { self.arena.alloc(self.lower_pat_mut(pattern)) } @@ -283,7 +285,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { hir_id: hir::HirId, lower_sub: impl FnOnce(&mut Self) -> Option<&'hir hir::Pat<'hir>>, ) -> hir::PatKind<'hir> { - match self.resolver.get_partial_res(p.id).map(|d| d.expect_full_res()) { + match self.get_partial_res(p.id).map(|d| d.expect_full_res()) { // `None` can occur in body-less function signatures res @ (None | Some(Res::Local(_))) => { let binding_id = match res { @@ -524,7 +526,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // We're generating a range end that didn't exist in the AST, // so the def collector didn't create the def ahead of time. That's why we have to do // it here. - let def_id = self.create_def(node_id, None, DefKind::AnonConst, span); + let def_id = + self.create_def(node_id, None, DefKind::AnonConst, DefPathData::LateAnonConst, span); let hir_id = self.lower_node_id(node_id); let unstable_span = self.mark_span_with_reason( diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index c80ef275c801a..0969a82784a1f 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -19,7 +19,7 @@ use super::{ LifetimeRes, LoweringContext, ParamMode, ResolverAstLoweringExt, }; -impl<'a, 'hir> LoweringContext<'a, 'hir> { +impl<'hir> LoweringContext<'hir> { #[instrument(level = "trace", skip(self))] pub(crate) fn lower_qpath( &mut self, @@ -38,8 +38,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Reject cases like `::Assoc` and `::Assoc`. .map(|q| self.lower_ty(&q.ty, ImplTraitContext::Disallowed(ImplTraitPosition::Path))); - let partial_res = - self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err)); + let partial_res = self.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err)); let base_res = partial_res.base_res(); let unresolved_segments = partial_res.unresolved_segments(); diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index 7c69baba62e8b..a06540f832507 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -681,46 +681,30 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { return (false, false, None); } let my_def = self.body.source.def_id(); - let my_hir = self.infcx.tcx.local_def_id_to_hir_id(my_def.as_local().unwrap()); let Some(td) = self.infcx.tcx.impl_of_method(my_def).and_then(|x| self.infcx.tcx.trait_id_of_impl(x)) else { return (false, false, None); }; + + let implemented_trait_item = self.infcx.tcx.associated_item(my_def).trait_item_def_id; + ( true, td.is_local(), - td.as_local().and_then(|tld| match self.infcx.tcx.hir_node_by_def_id(tld) { - Node::Item(hir::Item { - kind: hir::ItemKind::Trait(_, _, _, _, _, items), .. - }) => { - let mut f_in_trait_opt = None; - for hir::TraitItemRef { id: fi, kind: k, .. } in *items { - let hi = fi.hir_id(); - if !matches!(k, hir::AssocItemKind::Fn { .. }) { - continue; - } - if self.infcx.tcx.hir_name(hi) != self.infcx.tcx.hir_name(my_hir) { - continue; - } - f_in_trait_opt = Some(hi); - break; - } - f_in_trait_opt.and_then(|f_in_trait| { - if let Node::TraitItem(ti) = self.infcx.tcx.hir_node(f_in_trait) - && let hir::TraitItemKind::Fn(sig, _) = ti.kind - && let Some(ty) = sig.decl.inputs.get(local.index() - 1) - && let hir::TyKind::Ref(_, mut_ty) = ty.kind - && let hir::Mutability::Not = mut_ty.mutbl - && sig.decl.implicit_self.has_implicit_self() - { - Some(ty.span) - } else { - None - } - }) + implemented_trait_item.and_then(|f_in_trait| { + let f_in_trait = f_in_trait.as_local()?; + if let Node::TraitItem(ti) = self.infcx.tcx.hir_node_by_def_id(f_in_trait) + && let hir::TraitItemKind::Fn(sig, _) = ti.kind + && let Some(ty) = sig.decl.inputs.get(local.index() - 1) + && let hir::TyKind::Ref(_, mut_ty) = ty.kind + && let hir::Mutability::Not = mut_ty.mutbl + && sig.decl.implicit_self.has_implicit_self() + { + Some(ty.span) + } else { + None } - _ => None, }), ) } diff --git a/compiler/rustc_driver_impl/src/pretty.rs b/compiler/rustc_driver_impl/src/pretty.rs index 688307a941f30..478b15f516a49 100644 --- a/compiler/rustc_driver_impl/src/pretty.rs +++ b/compiler/rustc_driver_impl/src/pretty.rs @@ -211,7 +211,7 @@ impl<'tcx> PrintExtra<'tcx> { { match self { PrintExtra::AfterParsing { krate, .. } => f(krate), - PrintExtra::NeedsAstMap { tcx } => f(&tcx.resolver_for_lowering().borrow().1), + PrintExtra::NeedsAstMap { tcx } => f(&tcx.resolver_for_lowering().1.borrow()), } } @@ -261,7 +261,7 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) { } AstTreeExpanded => { debug!("pretty-printing expanded AST"); - format!("{:#?}", ex.tcx().resolver_for_lowering().borrow().1) + format!("{:#?}", ex.tcx().resolver_for_lowering().1.borrow()) } Hir(s) => { debug!("pretty printing HIR {:?}", s); diff --git a/compiler/rustc_hir/src/definitions.rs b/compiler/rustc_hir/src/definitions.rs index f93b9e5af5345..5127f613cc497 100644 --- a/compiler/rustc_hir/src/definitions.rs +++ b/compiler/rustc_hir/src/definitions.rs @@ -306,6 +306,10 @@ pub enum DefPathData { Ctor, /// A constant expression (see `{ast,hir}::AnonConst`). AnonConst, + /// A constant expression created during AST->HIR lowering.. + LateAnonConst, + /// A fresh anonymous lifetime created by desugaring elided lifetimes. + DesugaredAnonymousLifetime, /// An existential `impl Trait` type node. /// Argument position `impl Trait` have a `TypeNs` with their pretty-printed name. OpaqueTy, @@ -450,6 +454,8 @@ impl DefPathData { TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) | OpaqueLifetime(name) => Some(name), + DesugaredAnonymousLifetime => Some(kw::UnderscoreLifetime), + Impl | ForeignMod | CrateRoot @@ -458,6 +464,7 @@ impl DefPathData { | Closure | Ctor | AnonConst + | LateAnonConst | OpaqueTy | AnonAssocTy(..) | SyntheticCoroutineBody @@ -471,6 +478,8 @@ impl DefPathData { TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) | AnonAssocTy(name) | OpaqueLifetime(name) => Some(name), + DesugaredAnonymousLifetime => Some(kw::UnderscoreLifetime), + Impl | ForeignMod | CrateRoot @@ -479,6 +488,7 @@ impl DefPathData { | Closure | Ctor | AnonConst + | LateAnonConst | OpaqueTy | SyntheticCoroutineBody | NestedStatic => None, @@ -498,7 +508,8 @@ impl DefPathData { GlobalAsm => DefPathDataName::Anon { namespace: sym::global_asm }, Closure => DefPathDataName::Anon { namespace: sym::closure }, Ctor => DefPathDataName::Anon { namespace: sym::constructor }, - AnonConst => DefPathDataName::Anon { namespace: sym::constant }, + AnonConst | LateAnonConst => DefPathDataName::Anon { namespace: sym::constant }, + DesugaredAnonymousLifetime => DefPathDataName::Named(kw::UnderscoreLifetime), OpaqueTy => DefPathDataName::Anon { namespace: sym::opaque }, AnonAssocTy(..) => DefPathDataName::Anon { namespace: sym::anon_assoc }, SyntheticCoroutineBody => DefPathDataName::Anon { namespace: sym::synthetic }, diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index ca6405ea20944..1aafe58509e2a 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -18,6 +18,7 @@ use rustc_attr_data_structures::AttributeKind; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::tagged_ptr::TaggedRef; +use rustc_data_structures::unord::UnordMap; use rustc_index::IndexVec; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_span::def_id::LocalDefId; @@ -1474,7 +1475,7 @@ impl<'tcx> AttributeMap<'tcx> { pub struct OwnerNodes<'tcx> { /// Pre-computed hash of the full HIR. Used in the crate hash. Only present /// when incr. comp. is enabled. - pub opt_hash_including_bodies: Option, + pub opt_hash: Option, /// Full HIR for the current owner. // The zeroth node's parent should never be accessed: the owner's parent is computed by the // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally @@ -1507,13 +1508,13 @@ impl fmt::Debug for OwnerNodes<'_> { }), ) .field("bodies", &self.bodies) - .field("opt_hash_including_bodies", &self.opt_hash_including_bodies) + .field("opt_hash", &self.opt_hash) .finish() } } /// Full information resulting from lowering an AST node. -#[derive(Debug, HashStable_Generic)] +#[derive(Debug)] pub struct OwnerInfo<'hir> { /// Contents of the HIR. pub nodes: OwnerNodes<'hir>, @@ -1523,11 +1524,14 @@ pub struct OwnerInfo<'hir> { pub attrs: AttributeMap<'hir>, /// Map indicating what traits are in scope for places where this /// is relevant; generated by resolve. - pub trait_map: ItemLocalMap>, - + pub trait_map: ItemLocalMap<&'hir [TraitCandidate]>, /// Lints delayed during ast lowering to be emitted /// after hir has completely built pub delayed_lints: DelayedLints, + /// Owners generated as side-effect by lowering. + pub children: UnordMap>, + // Only present when the crate hash is needed. + pub opt_hash: Option, } impl<'tcx> OwnerInfo<'tcx> { @@ -1541,36 +1545,23 @@ impl<'tcx> OwnerInfo<'tcx> { pub enum MaybeOwner<'tcx> { Owner(&'tcx OwnerInfo<'tcx>), NonOwner(HirId), - /// Used as a placeholder for unused LocalDefId. - Phantom, } impl<'tcx> MaybeOwner<'tcx> { + #[inline] pub fn as_owner(self) -> Option<&'tcx OwnerInfo<'tcx>> { match self { MaybeOwner::Owner(i) => Some(i), - MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None, + MaybeOwner::NonOwner(_) => None, } } + #[inline] pub fn unwrap(self) -> &'tcx OwnerInfo<'tcx> { self.as_owner().unwrap_or_else(|| panic!("Not a HIR owner")) } } -/// The top-level data structure that stores the entire contents of -/// the crate currently being compiled. -/// -/// For more details, see the [rustc dev guide]. -/// -/// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html -#[derive(Debug)] -pub struct Crate<'hir> { - pub owners: IndexVec>, - // Only present when incr. comp. is enabled. - pub opt_hir_hash: Option, -} - #[derive(Debug, Clone, Copy, HashStable_Generic)] pub struct Closure<'hir> { pub def_id: LocalDefId, @@ -3171,6 +3162,8 @@ pub struct ImplItem<'hir> { pub span: Span, pub vis_span: Span, pub has_delayed_lints: bool, + /// When we are in a trait impl, link to the trait-item's id. + pub trait_item_def_id: Option, } impl<'hir> ImplItem<'hir> { @@ -4135,7 +4128,7 @@ impl<'hir> Item<'hir> { expect_mod, (Ident, &'hir Mod<'hir>), ItemKind::Mod(ident, m), (*ident, m); - expect_foreign_mod, (ExternAbi, &'hir [ForeignItemRef]), + expect_foreign_mod, (ExternAbi, &'hir [ForeignItemId]), ItemKind::ForeignMod { abi, items }, (*abi, items); expect_global_asm, &'hir InlineAsm<'hir>, ItemKind::GlobalAsm { asm, .. }, asm; @@ -4159,7 +4152,7 @@ impl<'hir> Item<'hir> { Ident, &'hir Generics<'hir>, GenericBounds<'hir>, - &'hir [TraitItemRef] + &'hir [TraitItemId] ), ItemKind::Trait(is_auto, safety, ident, generics, bounds, items), (*is_auto, *safety, *ident, generics, bounds, items); @@ -4312,7 +4305,7 @@ pub enum ItemKind<'hir> { /// A module. Mod(Ident, &'hir Mod<'hir>), /// An external module, e.g. `extern { .. }`. - ForeignMod { abi: ExternAbi, items: &'hir [ForeignItemRef] }, + ForeignMod { abi: ExternAbi, items: &'hir [ForeignItemId] }, /// Module-level inline assembly (from `global_asm!`). GlobalAsm { asm: &'hir InlineAsm<'hir>, @@ -4332,7 +4325,7 @@ pub enum ItemKind<'hir> { /// A union definition, e.g., `union Foo {x: A, y: B}`. Union(Ident, &'hir Generics<'hir>, VariantData<'hir>), /// A trait definition. - Trait(IsAuto, Safety, Ident, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]), + Trait(IsAuto, Safety, Ident, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemId]), /// A trait alias. TraitAlias(Ident, &'hir Generics<'hir>, GenericBounds<'hir>), @@ -4359,7 +4352,7 @@ pub struct Impl<'hir> { pub of_trait: Option>, pub self_ty: &'hir Ty<'hir>, - pub items: &'hir [ImplItemRef], + pub items: &'hir [ImplItemId], } impl ItemKind<'_> { @@ -4402,43 +4395,6 @@ impl ItemKind<'_> { } } -/// A reference from an trait to one of its associated items. This -/// contains the item's id, naturally, but also the item's name and -/// some other high-level details (like whether it is an associated -/// type or method, and whether it is public). This allows other -/// passes to find the impl they want without loading the ID (which -/// means fewer edges in the incremental compilation graph). -#[derive(Debug, Clone, Copy, HashStable_Generic)] -pub struct TraitItemRef { - pub id: TraitItemId, - pub ident: Ident, - pub kind: AssocItemKind, - pub span: Span, -} - -/// A reference from an impl to one of its associated items. This -/// contains the item's ID, naturally, but also the item's name and -/// some other high-level details (like whether it is an associated -/// type or method, and whether it is public). This allows other -/// passes to find the impl they want without loading the ID (which -/// means fewer edges in the incremental compilation graph). -#[derive(Debug, Clone, Copy, HashStable_Generic)] -pub struct ImplItemRef { - pub id: ImplItemId, - pub ident: Ident, - pub kind: AssocItemKind, - pub span: Span, - /// When we are in a trait impl, link to the trait-item's id. - pub trait_item_def_id: Option, -} - -#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)] -pub enum AssocItemKind { - Const, - Fn { has_self: bool }, - Type, -} - // The bodies for items are stored "out of line", in a separate // hashmap in the `Crate`. Here we just record the hir-id of the item // so it can fetched later. @@ -4455,19 +4411,6 @@ impl ForeignItemId { } } -/// A reference from a foreign block to one of its items. This -/// contains the item's ID, naturally, but also the item's name and -/// some other high-level details (like whether it is an associated -/// type or method, and whether it is public). This allows other -/// passes to find the impl they want without loading the ID (which -/// means fewer edges in the incremental compilation graph). -#[derive(Debug, Clone, Copy, HashStable_Generic)] -pub struct ForeignItemRef { - pub id: ForeignItemId, - pub ident: Ident, - pub span: Span, -} - #[derive(Debug, Clone, Copy, HashStable_Generic)] pub struct ForeignItem<'hir> { pub ident: Ident, @@ -4968,7 +4911,7 @@ mod size_asserts { static_assert_size!(GenericBound<'_>, 64); static_assert_size!(Generics<'_>, 56); static_assert_size!(Impl<'_>, 80); - static_assert_size!(ImplItem<'_>, 88); + static_assert_size!(ImplItem<'_>, 96); static_assert_size!(ImplItemKind<'_>, 40); static_assert_size!(Item<'_>, 88); static_assert_size!(ItemKind<'_>, 64); diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index a0bc318e2ca66..b79519f29186b 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -435,17 +435,17 @@ pub trait Visitor<'v>: Sized { fn visit_trait_item(&mut self, ti: &'v TraitItem<'v>) -> Self::Result { walk_trait_item(self, ti) } - fn visit_trait_item_ref(&mut self, ii: &'v TraitItemRef) -> Self::Result { - walk_trait_item_ref(self, ii) + fn visit_trait_item_ref(&mut self, ii: &'v TraitItemId) -> Self::Result { + walk_trait_item_ref(self, *ii) } fn visit_impl_item(&mut self, ii: &'v ImplItem<'v>) -> Self::Result { walk_impl_item(self, ii) } - fn visit_foreign_item_ref(&mut self, ii: &'v ForeignItemRef) -> Self::Result { - walk_foreign_item_ref(self, ii) + fn visit_foreign_item_ref(&mut self, ii: &'v ForeignItemId) -> Self::Result { + walk_foreign_item_ref(self, *ii) } - fn visit_impl_item_ref(&mut self, ii: &'v ImplItemRef) -> Self::Result { - walk_impl_item_ref(self, ii) + fn visit_impl_item_ref(&mut self, ii: &'v ImplItemId) -> Self::Result { + walk_impl_item_ref(self, *ii) } fn visit_trait_ref(&mut self, t: &'v TraitRef<'v>) -> Self::Result { walk_trait_ref(self, t) @@ -499,9 +499,6 @@ pub trait Visitor<'v>: Sized { fn visit_attribute(&mut self, _attr: &'v Attribute) -> Self::Result { Self::Result::output() } - fn visit_associated_item_kind(&mut self, kind: &'v AssocItemKind) -> Self::Result { - walk_associated_item_kind(self, kind) - } fn visit_defaultness(&mut self, defaultness: &'v Defaultness) -> Self::Result { walk_defaultness(self, defaultness) } @@ -1248,14 +1245,8 @@ pub fn walk_trait_item<'v, V: Visitor<'v>>( V::Result::output() } -pub fn walk_trait_item_ref<'v, V: Visitor<'v>>( - visitor: &mut V, - trait_item_ref: &'v TraitItemRef, -) -> V::Result { - let TraitItemRef { id, ident, ref kind, span: _ } = *trait_item_ref; - try_visit!(visitor.visit_nested_trait_item(id)); - try_visit!(visitor.visit_ident(ident)); - visitor.visit_associated_item_kind(kind) +pub fn walk_trait_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, id: TraitItemId) -> V::Result { + visitor.visit_nested_trait_item(id) } pub fn walk_impl_item<'v, V: Visitor<'v>>( @@ -1271,6 +1262,7 @@ pub fn walk_impl_item<'v, V: Visitor<'v>>( span: _, vis_span: _, has_delayed_lints: _, + trait_item_def_id: _, } = *impl_item; try_visit!(visitor.visit_ident(ident)); @@ -1293,23 +1285,12 @@ pub fn walk_impl_item<'v, V: Visitor<'v>>( } } -pub fn walk_foreign_item_ref<'v, V: Visitor<'v>>( - visitor: &mut V, - foreign_item_ref: &'v ForeignItemRef, -) -> V::Result { - let ForeignItemRef { id, ident, span: _ } = *foreign_item_ref; - try_visit!(visitor.visit_nested_foreign_item(id)); - visitor.visit_ident(ident) +pub fn walk_foreign_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, id: ForeignItemId) -> V::Result { + visitor.visit_nested_foreign_item(id) } -pub fn walk_impl_item_ref<'v, V: Visitor<'v>>( - visitor: &mut V, - impl_item_ref: &'v ImplItemRef, -) -> V::Result { - let ImplItemRef { id, ident, ref kind, span: _, trait_item_def_id: _ } = *impl_item_ref; - try_visit!(visitor.visit_nested_impl_item(id)); - try_visit!(visitor.visit_ident(ident)); - visitor.visit_associated_item_kind(kind) +pub fn walk_impl_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, id: ImplItemId) -> V::Result { + visitor.visit_nested_impl_item(id) } pub fn walk_trait_ref<'v, V: Visitor<'v>>( @@ -1483,13 +1464,6 @@ pub fn walk_assoc_item_constraint<'v, V: Visitor<'v>>( V::Result::output() } -pub fn walk_associated_item_kind<'v, V: Visitor<'v>>(_: &mut V, _: &'v AssocItemKind) -> V::Result { - // No visitable content here: this fn exists so you can call it if - // the right thing to do, should content be added in the future, - // would be to walk it. - V::Result::output() -} - pub fn walk_defaultness<'v, V: Visitor<'v>>(_: &mut V, _: &'v Defaultness) -> V::Result { // No visitable content here: this fn exists so you can call it if // the right thing to do, should content be added in the future, diff --git a/compiler/rustc_hir/src/stable_hash_impls.rs b/compiler/rustc_hir/src/stable_hash_impls.rs index 6acf1524b608f..c20cb81d6ed2d 100644 --- a/compiler/rustc_hir/src/stable_hash_impls.rs +++ b/compiler/rustc_hir/src/stable_hash_impls.rs @@ -3,7 +3,7 @@ use rustc_span::def_id::DefPathHash; use crate::HashIgnoredAttrId; use crate::hir::{ - AttributeMap, BodyId, Crate, ForeignItemId, ImplItemId, ItemId, OwnerNodes, TraitItemId, + AttributeMap, BodyId, ForeignItemId, ImplItemId, ItemId, OwnerInfo, OwnerNodes, TraitItemId, }; use crate::hir_id::{HirId, ItemLocalId}; use crate::lints::DelayedLints; @@ -92,18 +92,17 @@ impl ToStableHashKey for ForeignItemId // in "DefPath Mode". impl<'tcx, HirCtx: crate::HashStableContext> HashStable for OwnerNodes<'tcx> { + #[inline] fn hash_stable(&self, hcx: &mut HirCtx, hasher: &mut StableHasher) { - // We ignore the `nodes` and `bodies` fields since these refer to information included in - // `hash` which is hashed in the collector and used for the crate hash. - // `local_id_to_def_id` is also ignored because is dependent on the body, then just hashing - // the body satisfies the condition of two nodes being different have different - // `hash_stable` results. - let OwnerNodes { opt_hash_including_bodies, nodes: _, bodies: _ } = *self; - opt_hash_including_bodies.unwrap().hash_stable(hcx, hasher); + // We ignore the other fields since these refer to information included in + // `opt_hash` which is hashed in the collector and used for the crate hash. + let OwnerNodes { opt_hash, .. } = *self; + opt_hash.unwrap().hash_stable(hcx, hasher); } } impl HashStable for DelayedLints { + #[inline] fn hash_stable(&self, hcx: &mut HirCtx, hasher: &mut StableHasher) { let DelayedLints { opt_hash, .. } = *self; opt_hash.unwrap().hash_stable(hcx, hasher); @@ -111,6 +110,7 @@ impl HashStable for DelayedLints { } impl<'tcx, HirCtx: crate::HashStableContext> HashStable for AttributeMap<'tcx> { + #[inline] fn hash_stable(&self, hcx: &mut HirCtx, hasher: &mut StableHasher) { // We ignore the `map` since it refers to information included in `opt_hash` which is // hashed in the collector and used for the crate hash. @@ -119,10 +119,13 @@ impl<'tcx, HirCtx: crate::HashStableContext> HashStable for AttributeMap } } -impl HashStable for Crate<'_> { +impl<'tcx, HirCtx: crate::HashStableContext> HashStable for OwnerInfo<'tcx> { + #[inline] fn hash_stable(&self, hcx: &mut HirCtx, hasher: &mut StableHasher) { - let Crate { owners: _, opt_hir_hash } = self; - opt_hir_hash.unwrap().hash_stable(hcx, hasher) + // We ignore the rest since it refers to information included in `opt_hash` which is + // hashed in the collector and used for the crate hash. + let OwnerInfo { opt_hash, .. } = *self; + opt_hash.unwrap().hash_stable(hcx, hasher); } } diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index f4fcb13b1a126..5f5d3e7cb6ef3 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -931,8 +931,8 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), check_abi(tcx, it.hir_id(), it.span, abi); - for item in items { - let def_id = item.id.owner_id.def_id; + for &item in items { + let def_id = item.owner_id.def_id; let generics = tcx.generics_of(def_id); let own_counts = generics.own_counts(); @@ -944,13 +944,14 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), (0, _) => ("const", "consts", None), _ => ("type or const", "types or consts", None), }; + let span = tcx.def_span(def_id); struct_span_code_err!( tcx.dcx(), - item.span, + span, E0044, "foreign items may not have {kinds} parameters", ) - .with_span_label(item.span, format!("can't have {kinds} parameters")) + .with_span_label(span, format!("can't have {kinds} parameters")) .with_help( // FIXME: once we start storing spans for type arguments, turn this // into a suggestion. @@ -964,22 +965,23 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), .emit(); } - let item = tcx.hir_foreign_item(item.id); - tcx.ensure_ok().generics_of(item.owner_id); - tcx.ensure_ok().type_of(item.owner_id); - tcx.ensure_ok().predicates_of(item.owner_id); + tcx.ensure_ok().generics_of(def_id); + tcx.ensure_ok().type_of(def_id); + tcx.ensure_ok().predicates_of(def_id); if tcx.is_conditionally_const(def_id) { tcx.ensure_ok().explicit_implied_const_bounds(def_id); tcx.ensure_ok().const_conditions(def_id); } - match item.kind { - hir::ForeignItemKind::Fn(sig, ..) => { - tcx.ensure_ok().codegen_fn_attrs(item.owner_id); - tcx.ensure_ok().fn_sig(item.owner_id); + match tcx.def_kind(def_id) { + DefKind::Fn => { + tcx.ensure_ok().codegen_fn_attrs(def_id); + tcx.ensure_ok().fn_sig(def_id); + let item = tcx.hir_foreign_item(item); + let hir::ForeignItemKind::Fn(sig, ..) = item.kind else { bug!() }; require_c_abi_if_c_variadic(tcx, sig.decl, abi, item.span); } - hir::ForeignItemKind::Static(..) => { - tcx.ensure_ok().codegen_fn_attrs(item.owner_id); + DefKind::Static { .. } => { + tcx.ensure_ok().codegen_fn_attrs(def_id); } _ => (), } diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index cebf7d1b5324e..396d606599bbf 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -59,7 +59,7 @@ fn equate_intrinsic_type<'tcx>( /// Returns the unsafety of the given intrinsic. fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hir::Safety { - let is_in_list = match tcx.item_name(intrinsic_id.into()) { + let is_in_list = match tcx.item_name(intrinsic_id) { // When adding a new intrinsic to this list, // it's usually worth updating that intrinsic's documentation // to note that it's safe to call, since @@ -143,7 +143,7 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi tcx.def_span(intrinsic_id), DiagMessage::from(format!( "intrinsic safety mismatch between list of intrinsics within the compiler and core library intrinsics for intrinsic `{}`", - tcx.item_name(intrinsic_id.into()) + tcx.item_name(intrinsic_id) ) )).emit(); } diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 25064c327d051..d36f1761e4902 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -844,11 +844,9 @@ fn adt_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AdtDef<'_> { fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { let item = tcx.hir_expect_item(def_id); - let (is_alias, is_auto, safety, items) = match item.kind { - hir::ItemKind::Trait(is_auto, safety, .., items) => { - (false, is_auto == hir::IsAuto::Yes, safety, items) - } - hir::ItemKind::TraitAlias(..) => (true, false, hir::Safety::Safe, &[][..]), + let (is_alias, is_auto, safety) = match item.kind { + hir::ItemKind::Trait(is_auto, safety, ..) => (false, is_auto == hir::IsAuto::Yes, safety), + hir::ItemKind::TraitAlias(..) => (true, false, hir::Safety::Safe), _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"), }; @@ -909,13 +907,16 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { // functions in the trait with default implementations .and_then(|(list, attr_span)| { let errors = list.iter().filter_map(|ident| { - let item = items.iter().find(|item| item.ident == *ident); + let item = tcx + .associated_items(def_id) + .filter_by_name_unhygienic(ident.name) + .find(|item| item.ident(tcx) == *ident); match item { - Some(item) if matches!(item.kind, hir::AssocItemKind::Fn { .. }) => { - if !tcx.defaultness(item.id.owner_id).has_value() { + Some(item) if matches!(item.kind, ty::AssocKind::Fn { .. }) => { + if !item.defaultness(tcx).has_value() { tcx.dcx().emit_err(errors::FunctionNotHaveDefaultImplementation { - span: item.span, + span: tcx.def_span(item.def_id), note_span: attr_span, }); @@ -926,7 +927,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { } Some(item) => { tcx.dcx().emit_err(errors::MustImplementNotFunction { - span: item.span, + span: tcx.def_span(item.def_id), span_note: errors::MustImplementNotFunctionSpanNote { span: attr_span }, note: errors::MustImplementNotFunctionNote {}, }); diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index c523a03e012e4..a6d892115481e 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -654,8 +654,8 @@ impl<'a> State<'a> { let (cb, ib) = self.head("extern"); self.word_nbsp(abi.to_string()); self.bopen(ib); - for item in items { - self.ann.nested(self, Nested::ForeignItem(item.id)); + for &foreign_item in items { + self.ann.nested(self, Nested::ForeignItem(foreign_item)); } self.bclose(item.span, cb); } @@ -730,8 +730,8 @@ impl<'a> State<'a> { self.space(); self.bopen(ib); - for impl_item in items { - self.ann.nested(self, Nested::ImplItem(impl_item.id)); + for &impl_item in items { + self.ann.nested(self, Nested::ImplItem(impl_item)); } self.bclose(item.span, cb); } @@ -746,8 +746,8 @@ impl<'a> State<'a> { self.print_where_clause(generics); self.word(" "); self.bopen(ib); - for trait_item in trait_items { - self.ann.nested(self, Nested::TraitItem(trait_item.id)); + for &trait_item in trait_items { + self.ann.nested(self, Nested::TraitItem(trait_item)); } self.bclose(item.span, cb); } diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index a438cde018c63..4308b87da0b1b 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -387,7 +387,8 @@ fn print_macro_stats(ecx: &ExtCtxt<'_>) { fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) { let sess = tcx.sess; - let (resolver, krate) = &*tcx.resolver_for_lowering().borrow(); + let (resolver, krate) = tcx.resolver_for_lowering(); + let krate = &*krate.borrow(); let mut lint_buffer = resolver.lint_buffer.steal(); if sess.opts.unstable_opts.input_stats { @@ -463,7 +464,7 @@ fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) { tcx.registered_tools(()), Some(lint_buffer), rustc_lint::BuiltinCombinedEarlyLintPass::new(), - (&**krate, &*krate.attrs), + (&*krate, &*krate.attrs), ) } @@ -773,7 +774,7 @@ fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[P fn resolver_for_lowering_raw<'tcx>( tcx: TyCtxt<'tcx>, (): (), -) -> (&'tcx Steal<(ty::ResolverAstLowering, Arc)>, &'tcx ty::ResolverGlobalCtxt) { +) -> (&'tcx (ty::ResolverAstLowering, Steal), &'tcx ty::ResolverGlobalCtxt) { let arenas = Resolver::arenas(); let _ = tcx.registered_tools(()); // Uses `crate_for_resolver`. let (krate, pre_configured_attrs) = tcx.crate_for_resolver(()).steal(); @@ -795,7 +796,7 @@ fn resolver_for_lowering_raw<'tcx>( } = resolver.into_outputs(); let resolutions = tcx.arena.alloc(untracked_resolutions); - (tcx.arena.alloc(Steal::new((untracked_resolver_for_lowering, Arc::new(krate)))), resolutions) + (tcx.arena.alloc((untracked_resolver_for_lowering, Steal::new(krate))), resolutions) } pub fn write_dep_info(tcx: TyCtxt<'_>) { @@ -852,10 +853,10 @@ pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) { return; } let _timer = tcx.sess.timer("write_interface"); - let (_, krate) = &*tcx.resolver_for_lowering().borrow(); + let (_, krate) = tcx.resolver_for_lowering(); let krate = rustc_ast_pretty::pprust::print_crate_as_interface( - krate, + &*krate.borrow(), tcx.sess.psess.edition, &tcx.sess.psess.attr_id_generator, ); @@ -869,7 +870,8 @@ pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) { pub static DEFAULT_QUERY_PROVIDERS: LazyLock = LazyLock::new(|| { let providers = &mut Providers::default(); providers.analysis = analysis; - providers.hir_crate = rustc_ast_lowering::lower_to_hir; + providers.index_ast = rustc_ast_lowering::index_ast; + providers.lower_to_hir = rustc_ast_lowering::lower_to_hir; providers.resolver_for_lowering_raw = resolver_for_lowering_raw; providers.stripped_cfg_items = |tcx, _| &tcx.resolutions(()).stripped_cfg_items[..]; providers.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1; @@ -1021,6 +1023,8 @@ pub fn create_and_enter_global_ctxt FnOnce(TyCtxt<'tcx>) -> T>( /// Runs all analyses that we guarantee to run, even if errors were reported in earlier analyses. /// This function never fails. fn run_required_analyses(tcx: TyCtxt<'_>) { + tcx.ensure_done().early_lint_checks(()); + if tcx.sess.opts.unstable_opts.input_stats { rustc_passes::input_stats::print_hir_stats(tcx); } diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 172f3372483ae..255ff56f62b1d 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -28,7 +28,7 @@ use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; use rustc_hir::intravisit::FnKind as HirFnKind; -use rustc_hir::{Body, FnDecl, GenericParamKind, PatKind, PredicateOrigin}; +use rustc_hir::{Body, FnDecl, PatKind, PredicateOrigin}; use rustc_middle::bug; use rustc_middle::lint::LevelAndSource; use rustc_middle::ty::layout::LayoutOf; @@ -952,36 +952,34 @@ declare_lint! { declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]); +impl InvalidNoMangleItems { + fn check_no_mangle_on_generic_fn( + &self, + cx: &LateContext<'_>, + attr_span: Span, + def_id: LocalDefId, + ) { + let generics = cx.tcx.generics_of(def_id); + if generics.requires_monomorphization(cx.tcx) { + cx.emit_span_lint( + NO_MANGLE_GENERIC_ITEMS, + cx.tcx.def_span(def_id), + BuiltinNoMangleGeneric { suggestion: attr_span }, + ); + } + } +} + impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { let attrs = cx.tcx.hir_attrs(it.hir_id()); - let check_no_mangle_on_generic_fn = |attr_span: Span, - impl_generics: Option<&hir::Generics<'_>>, - generics: &hir::Generics<'_>, - span| { - for param in - generics.params.iter().chain(impl_generics.map(|g| g.params).into_iter().flatten()) - { - match param.kind { - GenericParamKind::Lifetime { .. } => {} - GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { - cx.emit_span_lint( - NO_MANGLE_GENERIC_ITEMS, - span, - BuiltinNoMangleGeneric { suggestion: attr_span }, - ); - break; - } - } - } - }; match it.kind { - hir::ItemKind::Fn { generics, .. } => { + hir::ItemKind::Fn { .. } => { if let Some(attr_span) = find_attr!(attrs, AttributeKind::ExportName {span, ..} => *span) .or_else(|| find_attr!(attrs, AttributeKind::NoMangle(span) => *span)) { - check_no_mangle_on_generic_fn(attr_span, None, generics, it.span); + self.check_no_mangle_on_generic_fn(cx, attr_span, it.owner_id.def_id); } } hir::ItemKind::Const(..) => { @@ -1006,24 +1004,19 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { ); } } - hir::ItemKind::Impl(hir::Impl { generics, items, .. }) => { - for it in *items { - if let hir::AssocItemKind::Fn { .. } = it.kind { - let attrs = cx.tcx.hir_attrs(it.id.hir_id()); - if let Some(attr_span) = - find_attr!(attrs, AttributeKind::ExportName {span, ..} => *span) - .or_else( - || find_attr!(attrs, AttributeKind::NoMangle(span) => *span), - ) - { - check_no_mangle_on_generic_fn( - attr_span, - Some(generics), - cx.tcx.hir_get_generics(it.id.owner_id.def_id).unwrap(), - it.span, - ); - } - } + _ => {} + } + } + + fn check_impl_item(&mut self, cx: &LateContext<'_>, it: &hir::ImplItem<'_>) { + let attrs = cx.tcx.hir_attrs(it.hir_id()); + match it.kind { + hir::ImplItemKind::Fn { .. } => { + if let Some(attr_span) = + find_attr!(attrs, AttributeKind::ExportName {span, ..} => *span) + .or_else(|| find_attr!(attrs, AttributeKind::NoMangle(span) => *span)) + { + self.check_no_mangle_on_generic_fn(cx, attr_span, it.owner_id.def_id); } } _ => {} diff --git a/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs b/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs index 5989ef9519cd7..dd16117db1c5e 100644 --- a/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs +++ b/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs @@ -1,7 +1,7 @@ use rustc_hir::{self as hir, LangItem}; use rustc_middle::ty; use rustc_session::{declare_lint, declare_lint_pass}; -use rustc_span::sym; +use rustc_span::{Ident, sym}; use rustc_trait_selection::traits::supertraits; use crate::lints::{SupertraitAsDerefTarget, SupertraitAsDerefTargetLabel}; @@ -79,11 +79,15 @@ impl<'tcx> LateLintPass<'tcx> for DerefIntoDynSupertrait { // erase regions in self type for better diagnostic presentation let (self_ty, target_principal, supertrait_principal) = tcx.erase_regions((self_ty, target_principal, supertrait_principal)); - let label2 = impl_ - .items - .iter() - .find_map(|i| (i.ident.name == sym::Target).then_some(i.span)) - .map(|label| SupertraitAsDerefTargetLabel { label }); + let label2 = tcx + .associated_items(item.owner_id) + .find_by_ident_and_kind( + tcx, + Ident::with_dummy_span(sym::Target), + ty::AssocTag::Type, + item.owner_id.to_def_id(), + ) + .map(|label| SupertraitAsDerefTargetLabel { label: tcx.def_span(label.def_id) }); let span = tcx.def_span(item.owner_id.def_id); cx.emit_span_lint( DEREF_INTO_DYN_SUPERTRAIT, diff --git a/compiler/rustc_metadata/src/foreign_modules.rs b/compiler/rustc_metadata/src/foreign_modules.rs index 24689ea61d036..8a6b2027083d6 100644 --- a/compiler/rustc_metadata/src/foreign_modules.rs +++ b/compiler/rustc_metadata/src/foreign_modules.rs @@ -19,7 +19,7 @@ pub(crate) fn collect(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> FxIndexMap, [decode] typeck_results: rustc_middle::ty::TypeckResults<'tcx>, [decode] borrowck_result: rustc_middle::mir::ConcreteOpaqueTypes<'tcx>, - [] resolver: rustc_data_structures::steal::Steal<( + [] resolver: ( rustc_middle::ty::ResolverAstLowering, - std::sync::Arc, - )>, + rustc_data_structures::steal::Steal + ), + [] index_ast: ( + rustc_index::IndexVec + >, + rustc_ast::NodeId, + ), [] crate_for_resolver: rustc_data_structures::steal::Steal<(rustc_ast::Crate, rustc_ast::AttrVec)>, [] resolutions: rustc_middle::ty::ResolverGlobalCtxt, [] const_allocs: rustc_middle::mir::interpret::Allocation, diff --git a/compiler/rustc_middle/src/hir/map.rs b/compiler/rustc_middle/src/hir/map.rs index 291707878a342..ad98a3fc355d2 100644 --- a/compiler/rustc_middle/src/hir/map.rs +++ b/compiler/rustc_middle/src/hir/map.rs @@ -1117,11 +1117,8 @@ impl<'tcx> pprust_hir::PpAnn for TyCtxt<'tcx> { } pub(super) fn crate_hash(tcx: TyCtxt<'_>, _: LocalCrate) -> Svh { - let krate = tcx.hir_crate(()); - let hir_body_hash = krate.opt_hir_hash.expect("HIR hash missing while computing crate hash"); - + let krate = tcx.hir_crate_items(()); let upstream_crates = upstream_crates(tcx); - let resolutions = tcx.resolutions(()); // We hash the final, remapped names of all local source files so we @@ -1156,7 +1153,12 @@ pub(super) fn crate_hash(tcx: TyCtxt<'_>, _: LocalCrate) -> Svh { let crate_hash: Fingerprint = tcx.with_stable_hashing_context(|mut hcx| { let mut stable_hasher = StableHasher::new(); - hir_body_hash.hash_stable(&mut hcx, &mut stable_hasher); + // hir_body_hash + for owner in krate.owners() { + if let Some(info) = tcx.lower_to_hir(owner.def_id).as_owner() { + info.hash_stable(&mut hcx, &mut stable_hasher); + } + } upstream_crates.hash_stable(&mut hcx, &mut stable_hasher); source_file_names.hash_stable(&mut hcx, &mut stable_hasher); debugger_visualizers.hash_stable(&mut hcx, &mut stable_hasher); diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index d7a8dce0536b2..01f80ef2fb339 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -208,19 +208,18 @@ pub fn provide(providers: &mut Providers) { providers.hir_crate_items = map::hir_crate_items; providers.crate_hash = map::crate_hash; providers.hir_module_items = map::hir_module_items; - providers.local_def_id_to_hir_id = |tcx, def_id| match tcx.hir_crate(()).owners[def_id] { + providers.local_def_id_to_hir_id = |tcx, def_id| match tcx.lower_to_hir(def_id) { MaybeOwner::Owner(_) => HirId::make_owner(def_id), MaybeOwner::NonOwner(hir_id) => hir_id, - MaybeOwner::Phantom => bug!("No HirId for {:?}", def_id), }; - providers.opt_hir_owner_nodes = - |tcx, id| tcx.hir_crate(()).owners.get(id)?.as_owner().map(|i| &i.nodes); + providers.opt_hir_owner_nodes = |tcx, id| tcx.lower_to_hir(id).as_owner().map(|i| &i.nodes); providers.hir_owner_parent = |tcx, owner_id| { tcx.opt_local_parent(owner_id.def_id).map_or(CRATE_HIR_ID, |parent_def_id| { let parent_owner_id = tcx.local_def_id_to_hir_id(parent_def_id).owner; HirId { owner: parent_owner_id, - local_id: tcx.hir_crate(()).owners[parent_owner_id.def_id] + local_id: tcx + .lower_to_hir(parent_owner_id) .unwrap() .parenting .get(&owner_id.def_id) @@ -229,11 +228,10 @@ pub fn provide(providers: &mut Providers) { } }) }; - providers.hir_attr_map = |tcx, id| { - tcx.hir_crate(()).owners[id.def_id].as_owner().map_or(AttributeMap::EMPTY, |o| &o.attrs) - }; + providers.hir_attr_map = + |tcx, id| tcx.lower_to_hir(id.def_id).as_owner().map_or(AttributeMap::EMPTY, |o| &o.attrs); providers.opt_ast_lowering_delayed_lints = - |tcx, id| tcx.hir_crate(()).owners[id.def_id].as_owner().map(|o| &o.delayed_lints); + |tcx, id| tcx.lower_to_hir(id.def_id).as_owner().map(|o| &o.delayed_lints); providers.def_span = |tcx, def_id| tcx.hir_span(tcx.local_def_id_to_hir_id(def_id)); providers.def_ident_span = |tcx, def_id| { let hir_id = tcx.local_def_id_to_hir_id(def_id); @@ -265,7 +263,6 @@ pub fn provide(providers: &mut Providers) { |tcx, trait_id| tcx.resolutions(()).trait_impls.get(&trait_id).map_or(&[], |xs| &xs[..]); providers.expn_that_defined = |tcx, id| tcx.resolutions(()).expn_that_defined.get(&id).copied().unwrap_or(ExpnId::root()); - providers.in_scope_traits_map = |tcx, id| { - tcx.hir_crate(()).owners[id.def_id].as_owner().map(|owner_info| &owner_info.trait_map) - }; + providers.in_scope_traits_map = + |tcx, id| tcx.lower_to_hir(id.def_id).as_owner().map(|owner_info| &owner_info.trait_map); } diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 17a29c9ae4b21..be02eb0b4b96f 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -83,7 +83,7 @@ use rustc_hir::def_id::{ CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap, LocalDefIdSet, LocalModDefId, }; use rustc_hir::lang_items::{LangItem, LanguageItems}; -use rustc_hir::{Crate, ItemLocalId, ItemLocalMap, PreciseCapturingArgKind, TraitCandidate}; +use rustc_hir::{ItemLocalId, ItemLocalMap, PreciseCapturingArgKind, TraitCandidate}; use rustc_index::IndexVec; use rustc_lint_defs::LintId; use rustc_macros::rustc_queries; @@ -198,12 +198,19 @@ rustc_queries! { desc { "getting the resolver outputs" } } - query resolver_for_lowering_raw(_: ()) -> (&'tcx Steal<(ty::ResolverAstLowering, Arc)>, &'tcx ty::ResolverGlobalCtxt) { + query resolver_for_lowering_raw(_: ()) -> (&'tcx (ty::ResolverAstLowering, Steal), &'tcx ty::ResolverGlobalCtxt) { eval_always no_hash desc { "getting the resolver for lowering" } } + query index_ast(_: ()) -> &'tcx (IndexVec>, ast::NodeId) { + arena_cache + eval_always + no_hash + desc { "getting the AST for lowering" } + } + /// Return the span for a definition. /// /// Contrary to `def_span` below, this query returns the full absolute span of the definition. @@ -215,17 +222,9 @@ rustc_queries! { desc { "getting the source span" } } - /// Represents crate as a whole (as distinct from the top-level crate module). - /// - /// If you call `tcx.hir_crate(())` we will have to assume that any change - /// means that you need to be recompiled. This is because the `hir_crate` - /// query gives you access to all other items. To avoid this fate, do not - /// call `tcx.hir_crate(())`; instead, prefer wrappers like - /// [`TyCtxt::hir_visit_all_item_likes_in_crate`]. - query hir_crate(key: ()) -> &'tcx Crate<'tcx> { - arena_cache + query lower_to_hir(key: LocalDefId) -> hir::MaybeOwner<'tcx> { eval_always - desc { "getting the crate HIR" } + desc { |tcx| "lower HIR for `{}`", tcx.def_path_str(key.to_def_id()) } } /// All items in the crate. @@ -1839,8 +1838,7 @@ rustc_queries! { query specializes(_: (DefId, DefId)) -> bool { desc { "computing whether impls specialize one another" } } - query in_scope_traits_map(_: hir::OwnerId) - -> Option<&'tcx ItemLocalMap>> { + query in_scope_traits_map(_: hir::OwnerId) -> Option<&'tcx ItemLocalMap<&'tcx [TraitCandidate]>> { desc { "getting traits in scope at a block" } } diff --git a/compiler/rustc_middle/src/ty/assoc.rs b/compiler/rustc_middle/src/ty/assoc.rs index 78b2e265b488c..789c4d0f410a2 100644 --- a/compiler/rustc_middle/src/ty/assoc.rs +++ b/compiler/rustc_middle/src/ty/assoc.rs @@ -256,6 +256,16 @@ impl AssocItems { self.items.get_by_key(Some(name)) } + /// Returns the associated item with the given identifier and `AssocKind`, if one exists. + /// The identifier is ignoring hygiene. This is meant to be used for lints and diagnostics. + pub fn filter_by_name_unhygienic_and_kind( + &self, + name: Symbol, + assoc_tag: AssocTag, + ) -> impl '_ + Iterator { + self.filter_by_name_unhygienic(name).filter(move |item| item.as_tag() == assoc_tag) + } + /// Returns the associated item with the given identifier and `AssocKind`, if one exists. /// The identifier is matched hygienically. pub fn find_by_ident_and_kind( diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 98b2ce01d89b2..2361538ac7b09 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1352,11 +1352,11 @@ impl<'tcx> TyCtxtFeed<'tcx, LocalDefId> { let bodies = Default::default(); let attrs = hir::AttributeMap::EMPTY; - let (opt_hash_including_bodies, _, _) = + let (opt_hash, _, _) = self.tcx.hash_owner_nodes(node, &bodies, &attrs.map, &[], attrs.define_opaque); let node = node.into(); self.opt_hir_owner_nodes(Some(self.tcx.arena.alloc(hir::OwnerNodes { - opt_hash_including_bodies, + opt_hash, nodes: IndexVec::from_elem_n( hir::ParentedNode { parent: hir::ItemLocalId::INVALID, node }, 1, @@ -3357,7 +3357,7 @@ impl<'tcx> TyCtxt<'tcx> { self.resolutions(()).module_children.get(&def_id).map_or(&[], |v| &v[..]) } - pub fn resolver_for_lowering(self) -> &'tcx Steal<(ty::ResolverAstLowering, Arc)> { + pub fn resolver_for_lowering(self) -> &'tcx (ty::ResolverAstLowering, Steal) { self.resolver_for_lowering_raw(()).0 } diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index f1b16ea54e634..e18fc51544fbf 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -38,7 +38,6 @@ use rustc_errors::{Diag, ErrorGuaranteed}; use rustc_hir::LangItem; use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap}; -use rustc_hir::definitions::DisambiguatorState; use rustc_index::IndexVec; use rustc_index::bit_set::BitMatrix; use rustc_macros::{ @@ -221,8 +220,6 @@ pub struct ResolverAstLowering { pub node_id_to_def_id: NodeMap, - pub disambiguator: DisambiguatorState, - pub trait_map: NodeMap>, /// List functions and methods for which lifetime elision was successful. pub lifetime_elision_allowed: FxHashSet, @@ -1593,7 +1590,8 @@ impl<'tcx> TyCtxt<'tcx> { } /// Look up the name of a definition across crates. This does not look at HIR. - pub fn opt_item_name(self, def_id: DefId) -> Option { + pub fn opt_item_name(self, def_id: impl IntoQueryParam) -> Option { + let def_id = def_id.into_query_param(); if let Some(cnum) = def_id.as_crate_root() { Some(self.crate_name(cnum)) } else { @@ -1613,7 +1611,8 @@ impl<'tcx> TyCtxt<'tcx> { /// [`opt_item_name`] instead. /// /// [`opt_item_name`]: Self::opt_item_name - pub fn item_name(self, id: DefId) -> Symbol { + pub fn item_name(self, id: impl IntoQueryParam) -> Symbol { + let id = id.into_query_param(); self.opt_item_name(id).unwrap_or_else(|| { bug!("item_name: no name for {:?}", self.def_path(id)); }) @@ -1622,7 +1621,8 @@ impl<'tcx> TyCtxt<'tcx> { /// Look up the name and span of a definition. /// /// See [`item_name`][Self::item_name] for more information. - pub fn opt_item_ident(self, def_id: DefId) -> Option { + pub fn opt_item_ident(self, def_id: impl IntoQueryParam) -> Option { + let def_id = def_id.into_query_param(); let def = self.opt_item_name(def_id)?; let span = self .def_ident_span(def_id) @@ -1633,7 +1633,8 @@ impl<'tcx> TyCtxt<'tcx> { /// Look up the name and span of a definition. /// /// See [`item_name`][Self::item_name] for more information. - pub fn item_ident(self, def_id: DefId) -> Ident { + pub fn item_ident(self, def_id: impl IntoQueryParam) -> Ident { + let def_id = def_id.into_query_param(); self.opt_item_ident(def_id).unwrap_or_else(|| { bug!("item_ident: no name for {:?}", self.def_path(def_id)); }) diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 1dba4a7b040a7..21f22876a6c03 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -2186,6 +2186,7 @@ fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace { DefPathData::ValueNs(..) | DefPathData::AnonConst + | DefPathData::LateAnonConst | DefPathData::Closure | DefPathData::Ctor => Namespace::ValueNS, diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 69b8be3d9cbc3..24833d3138485 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -1681,7 +1681,7 @@ pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option true, }; Some(ty::IntrinsicDef { - name: tcx.item_name(def_id.into()), + name: tcx.item_name(def_id), must_be_overridden, const_stable: tcx.has_attr(def_id, sym::rustc_intrinsic_const_stable_indirect), }) diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index b7b160c738d22..fab4434bc3478 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -1083,7 +1083,7 @@ fn find_fallback_pattern_typo<'tcx>( && infcx.can_eq(param_env, ty, cx.tcx.type_of(item.owner_id).instantiate_identity()) { // Look for local consts. - let item_name = cx.tcx.item_name(item.owner_id.into()); + let item_name = cx.tcx.item_name(item.owner_id); let vis = cx.tcx.visibility(item.owner_id); if vis.is_accessible_from(parent, cx.tcx) { accessible.push(item_name); diff --git a/compiler/rustc_mir_transform/src/coverage/mod.rs b/compiler/rustc_mir_transform/src/coverage/mod.rs index f253d1662cac8..221bd7516732e 100644 --- a/compiler/rustc_mir_transform/src/coverage/mod.rs +++ b/compiler/rustc_mir_transform/src/coverage/mod.rs @@ -327,7 +327,7 @@ fn extract_hir_info<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> ExtractedHir fn hash_mir_source<'tcx>(tcx: TyCtxt<'tcx>, hir_body: &'tcx hir::Body<'tcx>) -> u64 { // FIXME(cjgillot) Stop hashing HIR manually here. let owner = hir_body.id().hir_id.owner; - tcx.hir_owner_nodes(owner).opt_hash_including_bodies.unwrap().to_smaller_hash().as_u64() + tcx.hir_owner_nodes(owner).opt_hash.unwrap().to_smaller_hash().as_u64() } fn extract_hole_spans_from_hir<'tcx>(tcx: TyCtxt<'tcx>, hir_body: &hir::Body<'tcx>) -> Vec { diff --git a/compiler/rustc_passes/src/abi_test.rs b/compiler/rustc_passes/src/abi_test.rs index b139ed6a66c38..0ac42f03eb2f5 100644 --- a/compiler/rustc_passes/src/abi_test.rs +++ b/compiler/rustc_passes/src/abi_test.rs @@ -79,7 +79,7 @@ fn dump_abi_of_fn_item(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribut for meta_item in meta_items { match meta_item.name() { Some(sym::debug) => { - let fn_name = tcx.item_name(item_def_id.into()); + let fn_name = tcx.item_name(item_def_id); tcx.dcx().emit_err(AbiOf { span: tcx.def_span(item_def_id), fn_name, @@ -135,7 +135,7 @@ fn dump_abi_of_fn_type(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribut item_def_id, ); - let fn_name = tcx.item_name(item_def_id.into()); + let fn_name = tcx.item_name(item_def_id); tcx.dcx().emit_err(AbiOf { span, fn_name, fn_abi: format!("{:#?}", abi) }); } Some(sym::assert_eq) => { diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index c5ced4064140e..874fd4d430e99 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -18,8 +18,8 @@ use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalModDefId; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{ - self as hir, self, AssocItemKind, Attribute, CRATE_HIR_ID, CRATE_OWNER_ID, FnSig, ForeignItem, - HirId, Item, ItemKind, MethodKind, Safety, Target, TraitItem, + self as hir, self, Attribute, CRATE_HIR_ID, CRATE_OWNER_ID, FnSig, ForeignItem, HirId, Item, + ItemKind, MethodKind, Safety, Target, TraitItem, }; use rustc_macros::LintDiagnostic; use rustc_middle::hir::nested_filter; @@ -1119,7 +1119,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> { if generics.params.len() != 0 => {} ItemKind::Trait(_, _, _, generics, _, items) if generics.params.len() != 0 - || items.iter().any(|item| matches!(item.kind, AssocItemKind::Type)) => {} + || items.iter().any(|item| { + matches!(self.tcx.def_kind(item.owner_id), DefKind::AssocTy) + }) => {} ItemKind::TyAlias(_, generics, _) if generics.params.len() != 0 => {} _ => { self.dcx().emit_err(errors::DocSearchUnboxInvalid { span: meta.span() }); diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index cdfd1a2b07e34..948a901e091ed 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -415,8 +415,8 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { hir::ItemKind::Trait(.., trait_item_refs) => { // mark assoc ty live if the trait is live for trait_item in trait_item_refs { - if matches!(trait_item.kind, hir::AssocItemKind::Type) { - self.check_def_id(trait_item.id.owner_id.to_def_id()); + if matches!(self.tcx.def_kind(trait_item.owner_id), DefKind::AssocTy) { + self.check_def_id(trait_item.owner_id.to_def_id()); } } intravisit::walk_item(self, item) diff --git a/compiler/rustc_passes/src/debugger_visualizer.rs b/compiler/rustc_passes/src/debugger_visualizer.rs index 7a7a8175e5569..067b28e141f6a 100644 --- a/compiler/rustc_passes/src/debugger_visualizer.rs +++ b/compiler/rustc_passes/src/debugger_visualizer.rs @@ -82,11 +82,10 @@ impl<'ast> rustc_ast::visit::Visitor<'ast> for DebuggerVisualizerCollector<'_> { /// Traverses and collects the debugger visualizers for a specific crate. fn debugger_visualizers(tcx: TyCtxt<'_>, _: LocalCrate) -> Vec { - let resolver_and_krate = tcx.resolver_for_lowering().borrow(); - let krate = &*resolver_and_krate.1; + let krate = &tcx.resolver_for_lowering().1; let mut visitor = DebuggerVisualizerCollector { sess: tcx.sess, visualizers: Vec::new() }; - rustc_ast::visit::Visitor::visit_crate(&mut visitor, krate); + rustc_ast::visit::Visitor::visit_crate(&mut visitor, &*krate.borrow()); // We are collecting visualizers in AST-order, which is deterministic, // so we don't need to do any explicit sorting in order to get a diff --git a/compiler/rustc_passes/src/input_stats.rs b/compiler/rustc_passes/src/input_stats.rs index 40bc18939d636..1719f9867f46a 100644 --- a/compiler/rustc_passes/src/input_stats.rs +++ b/compiler/rustc_passes/src/input_stats.rs @@ -467,9 +467,9 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { hir_visit::walk_trait_item(self, ti) } - fn visit_trait_item_ref(&mut self, ti: &'v hir::TraitItemRef) { - self.record("TraitItemRef", Some(ti.id.hir_id()), ti); - hir_visit::walk_trait_item_ref(self, ti) + fn visit_trait_item_ref(&mut self, ti: &'v hir::TraitItemId) { + self.record("TraitItemId", Some(ti.hir_id()), ti); + hir_visit::walk_trait_item_ref(self, *ti) } fn visit_impl_item(&mut self, ii: &'v hir::ImplItem<'v>) { @@ -480,14 +480,14 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { hir_visit::walk_impl_item(self, ii) } - fn visit_foreign_item_ref(&mut self, fi: &'v hir::ForeignItemRef) { - self.record("ForeignItemRef", Some(fi.id.hir_id()), fi); - hir_visit::walk_foreign_item_ref(self, fi) + fn visit_foreign_item_ref(&mut self, fi: &'v hir::ForeignItemId) { + self.record("ForeignItemId", Some(fi.hir_id()), fi); + hir_visit::walk_foreign_item_ref(self, *fi) } - fn visit_impl_item_ref(&mut self, ii: &'v hir::ImplItemRef) { - self.record("ImplItemRef", Some(ii.id.hir_id()), ii); - hir_visit::walk_impl_item_ref(self, ii) + fn visit_impl_item_ref(&mut self, ii: &'v hir::ImplItemId) { + self.record("ImplItemId", Some(ii.hir_id()), ii); + hir_visit::walk_impl_item_ref(self, *ii) } fn visit_param_bound(&mut self, b: &'v hir::GenericBound<'v>) { diff --git a/compiler/rustc_passes/src/lang_items.rs b/compiler/rustc_passes/src/lang_items.rs index 3afed9784de51..cb2e702276a13 100644 --- a/compiler/rustc_passes/src/lang_items.rs +++ b/compiler/rustc_passes/src/lang_items.rs @@ -247,8 +247,8 @@ impl<'ast, 'tcx> LanguageItemCollector<'ast, 'tcx> { /// Traverses and collects all the lang items in all crates. fn get_lang_items(tcx: TyCtxt<'_>, (): ()) -> LanguageItems { - let resolver = tcx.resolver_for_lowering().borrow(); - let (resolver, krate) = &*resolver; + let (resolver, krate) = tcx.resolver_for_lowering(); + let krate = &*krate.borrow(); // Initialize the collector. let mut collector = LanguageItemCollector::new(tcx, resolver); diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 56d9f5bf78577..802cbb9fa2036 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -880,11 +880,16 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> { } for impl_item_ref in *items { - let impl_item = self.tcx.associated_item(impl_item_ref.id.owner_id); + let impl_item = self.tcx.associated_item(impl_item_ref.owner_id); if let Some(def_id) = impl_item.trait_item_def_id { // Pass `None` to skip deprecation warnings. - self.tcx.check_stability(def_id, None, impl_item_ref.span, None); + self.tcx.check_stability( + def_id, + None, + self.tcx.def_span(impl_item_ref.owner_id), + None, + ); } } } diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 963f4c77d809d..ab2433234aa90 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -26,7 +26,7 @@ use rustc_errors::{MultiSpan, listify}; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId, LocalModDefId}; use rustc_hir::intravisit::{self, InferKind, Visitor}; -use rustc_hir::{AmbigArg, AssocItemKind, ForeignItemKind, ItemId, ItemKind, PatKind}; +use rustc_hir::{AmbigArg, ForeignItemKind, ItemId, ItemKind, PatKind}; use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level}; use rustc_middle::query::Providers; use rustc_middle::ty::print::PrintTraitRefExt as _; @@ -672,14 +672,14 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { self.reach(item.owner_id.def_id, item_ev).generics().predicates(); for trait_item_ref in trait_item_refs { - self.update(trait_item_ref.id.owner_id.def_id, item_ev, Level::Reachable); + self.update(trait_item_ref.owner_id.def_id, item_ev, Level::Reachable); let tcx = self.tcx; - let mut reach = self.reach(trait_item_ref.id.owner_id.def_id, item_ev); + let mut reach = self.reach(trait_item_ref.owner_id.def_id, item_ev); reach.generics().predicates(); - if trait_item_ref.kind == AssocItemKind::Type - && !tcx.defaultness(trait_item_ref.id.owner_id).has_value() + if let DefKind::AssocTy = tcx.def_kind(trait_item_ref.owner_id) + && !tcx.defaultness(trait_item_ref.owner_id).has_value() { // No type to visit. } else { @@ -715,7 +715,7 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { self.reach(item.owner_id.def_id, item_ev).generics().predicates().ty().trait_ref(); for impl_item_ref in impl_.items { - let def_id = impl_item_ref.id.owner_id.def_id; + let def_id = impl_item_ref.owner_id.def_id; let max_vis = impl_.of_trait.is_none().then(|| self.tcx.local_visibility(def_id)); self.update_eff_vis(def_id, item_ev, max_vis, Level::Direct); @@ -755,8 +755,8 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { } hir::ItemKind::ForeignMod { items, .. } => { for foreign_item in items { - if let Some(foreign_item_ev) = self.get(foreign_item.id.owner_id.def_id) { - self.reach(foreign_item.id.owner_id.def_id, foreign_item_ev) + if let Some(foreign_item_ev) = self.get(foreign_item.owner_id.def_id) { + self.reach(foreign_item.owner_id.def_id, foreign_item_ev) .generics() .predicates() .ty(); @@ -1576,16 +1576,15 @@ impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> { fn check_assoc_item( &self, - def_id: LocalDefId, - assoc_item_kind: AssocItemKind, + item: &ty::AssocItem, vis: ty::Visibility, effective_vis: Option, ) { - let mut check = self.check(def_id, vis, effective_vis); + let mut check = self.check(item.def_id.expect_local(), vis, effective_vis); - let (check_ty, is_assoc_ty) = match assoc_item_kind { - AssocItemKind::Const | AssocItemKind::Fn { .. } => (true, false), - AssocItemKind::Type => (self.tcx.defaultness(def_id).has_value(), true), + let (check_ty, is_assoc_ty) = match item.kind { + ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. } => (true, false), + ty::AssocKind::Type { .. } => (item.defaultness(self.tcx).has_value(), true), }; check.in_assoc_ty = is_assoc_ty; @@ -1619,30 +1618,20 @@ impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> { self.check(def_id, item_visibility, effective_vis).generics().bounds(); } DefKind::Trait => { - let item = tcx.hir_item(id); - if let hir::ItemKind::Trait(.., trait_item_refs) = item.kind { - self.check_unnameable(item.owner_id.def_id, effective_vis); + self.check_unnameable(def_id, effective_vis); - self.check(item.owner_id.def_id, item_visibility, effective_vis) - .generics() - .predicates(); + self.check(def_id, item_visibility, effective_vis).generics().predicates(); - for trait_item_ref in trait_item_refs { - self.check_assoc_item( - trait_item_ref.id.owner_id.def_id, - trait_item_ref.kind, + for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() { + self.check_assoc_item(assoc_item, item_visibility, effective_vis); + + if assoc_item.is_type() { + self.check( + assoc_item.def_id.expect_local(), item_visibility, effective_vis, - ); - - if let AssocItemKind::Type = trait_item_ref.kind { - self.check( - trait_item_ref.id.owner_id.def_id, - item_visibility, - effective_vis, - ) - .bounds(); - } + ) + .bounds(); } } } @@ -1669,8 +1658,8 @@ impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> { DefKind::ForeignMod => { let item = tcx.hir_item(id); if let hir::ItemKind::ForeignMod { items, .. } = item.kind { - for foreign_item in items { - let foreign_item = tcx.hir_foreign_item(foreign_item.id); + for &foreign_item in items { + let foreign_item = tcx.hir_foreign_item(foreign_item); let ev = self.get(foreign_item.owner_id.def_id); let vis = tcx.local_visibility(foreign_item.owner_id.def_id); @@ -1714,69 +1703,52 @@ impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> { // Subitems of inherent impls have their own publicity. // A trait impl is public when both its type and its trait are public // Subitems of trait impls have inherited publicity. - DefKind::Impl { .. } => { - let item = tcx.hir_item(id); - if let hir::ItemKind::Impl(impl_) = item.kind { - let impl_vis = ty::Visibility::of_impl::( - item.owner_id.def_id, - tcx, - &Default::default(), - ); + DefKind::Impl { of_trait } => { + let impl_vis = ty::Visibility::of_impl::(def_id, tcx, &Default::default()); - // We are using the non-shallow version here, unlike when building the - // effective visisibilities table to avoid large number of false positives. - // For example in - // - // impl From for Pub { - // fn from(_: Priv) -> Pub {...} - // } - // - // lints shouldn't be emitted even if `from` effective visibility - // is larger than `Priv` nominal visibility and if `Priv` can leak - // in some scenarios due to type inference. - let impl_ev = EffectiveVisibility::of_impl::( - item.owner_id.def_id, - tcx, - self.effective_visibilities, - ); + // We are using the non-shallow version here, unlike when building the + // effective visisibilities table to avoid large number of false positives. + // For example in + // + // impl From for Pub { + // fn from(_: Priv) -> Pub {...} + // } + // + // lints shouldn't be emitted even if `from` effective visibility + // is larger than `Priv` nominal visibility and if `Priv` can leak + // in some scenarios due to type inference. + let impl_ev = + EffectiveVisibility::of_impl::(def_id, tcx, self.effective_visibilities); + + let mut check = self.check(def_id, impl_vis, Some(impl_ev)); + + // Generics and predicates of trait impls are intentionally not checked + // for private components (#90586). + if !of_trait { + check.generics().predicates(); + } - let mut check = self.check(item.owner_id.def_id, impl_vis, Some(impl_ev)); - // Generics and predicates of trait impls are intentionally not checked - // for private components (#90586). - if impl_.of_trait.is_none() { - check.generics().predicates(); - } - // Skip checking private components in associated types, due to lack of full - // normalization they produce very ridiculous false positives. - // FIXME: Remove this when full normalization is implemented. - check.skip_assoc_tys = true; - check.ty().trait_ref(); - - for impl_item_ref in impl_.items { - let impl_item_vis = if impl_.of_trait.is_none() { - min( - tcx.local_visibility(impl_item_ref.id.owner_id.def_id), - impl_vis, - tcx, - ) - } else { - impl_vis - }; + // Skip checking private components in associated types, due to lack of full + // normalization they produce very ridiculous false positives. + // FIXME: Remove this when full normalization is implemented. + check.skip_assoc_tys = true; + check.ty().trait_ref(); - let impl_item_ev = if impl_.of_trait.is_none() { - self.get(impl_item_ref.id.owner_id.def_id) - .map(|ev| ev.min(impl_ev, self.tcx)) - } else { - Some(impl_ev) - }; - - self.check_assoc_item( - impl_item_ref.id.owner_id.def_id, - impl_item_ref.kind, - impl_item_vis, - impl_item_ev, - ); - } + for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() { + let impl_item_vis = if !of_trait { + min(tcx.local_visibility(assoc_item.def_id.expect_local()), impl_vis, tcx) + } else { + impl_vis + }; + + let impl_item_ev = if !of_trait { + self.get(assoc_item.def_id.expect_local()) + .map(|ev| ev.min(impl_ev, self.tcx)) + } else { + Some(impl_ev) + }; + + self.check_assoc_item(assoc_item, impl_item_vis, impl_item_ev); } } _ => {} diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 7162f3a77d350..9d8b30ea6fca3 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1693,7 +1693,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { .into_items() .map(|(k, f)| (k, f.key())) .collect(), - disambiguator: self.disambiguator, trait_map: self.trait_map, lifetime_elision_allowed: self.lifetime_elision_allowed, lint_buffer: Steal::new(self.lint_buffer), diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs index f4a14b36ce5cf..b85dd73498135 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs @@ -713,7 +713,8 @@ fn encode_ty_name(tcx: TyCtxt<'_>, def_id: DefId) -> String { hir::definitions::DefPathData::ValueNs(..) => "v", hir::definitions::DefPathData::Closure => "C", hir::definitions::DefPathData::Ctor => "c", - hir::definitions::DefPathData::AnonConst => "k", + hir::definitions::DefPathData::AnonConst => "K", + hir::definitions::DefPathData::LateAnonConst => "k", hir::definitions::DefPathData::OpaqueTy => "i", hir::definitions::DefPathData::SyntheticCoroutineBody => "s", hir::definitions::DefPathData::NestedStatic => "n", @@ -723,6 +724,7 @@ fn encode_ty_name(tcx: TyCtxt<'_>, def_id: DefId) -> String { | hir::definitions::DefPathData::MacroNs(..) | hir::definitions::DefPathData::OpaqueLifetime(..) | hir::definitions::DefPathData::LifetimeNs(..) + | hir::definitions::DefPathData::DesugaredAnonymousLifetime | hir::definitions::DefPathData::AnonAssocTy(..) => { bug!("encode_ty_name: unexpected `{:?}`", disambiguated_data.data); } diff --git a/compiler/rustc_span/src/def_id.rs b/compiler/rustc_span/src/def_id.rs index 641bac88ad025..089042fac3dea 100644 --- a/compiler/rustc_span/src/def_id.rs +++ b/compiler/rustc_span/src/def_id.rs @@ -110,6 +110,7 @@ impl DefPathHash { /// Builds a new [DefPathHash] with the given [StableCrateId] and /// `local_hash`, where `local_hash` must be unique within its crate. + #[inline] pub fn new(stable_crate_id: StableCrateId, local_hash: Hash64) -> DefPathHash { DefPathHash(Fingerprint::new(stable_crate_id.0, local_hash)) } @@ -404,21 +405,21 @@ rustc_data_structures::define_id_collections!( impl HashStable for DefId { #[inline] fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { - self.to_stable_hash_key(hcx).hash_stable(hcx, hasher); + hcx.def_path_hash(*self).hash_stable(hcx, hasher); } } impl HashStable for LocalDefId { #[inline] fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { - self.to_stable_hash_key(hcx).hash_stable(hcx, hasher); + hcx.def_path_hash(self.to_def_id()).local_hash().hash_stable(hcx, hasher); } } impl HashStable for CrateNum { #[inline] fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { - self.to_stable_hash_key(hcx).hash_stable(hcx, hasher); + self.as_def_id().to_stable_hash_key(hcx).stable_crate_id().hash_stable(hcx, hasher); } } diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index fe0f8e6113ef7..eb679fb59790f 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -872,7 +872,8 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { DefPathData::ValueNs(_) => 'v', DefPathData::Closure => 'C', DefPathData::Ctor => 'c', - DefPathData::AnonConst => 'k', + DefPathData::AnonConst => 'K', + DefPathData::LateAnonConst => 'k', DefPathData::OpaqueTy => 'i', DefPathData::SyntheticCoroutineBody => 's', DefPathData::NestedStatic => 'n', @@ -884,6 +885,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { | DefPathData::Impl | DefPathData::MacroNs(_) | DefPathData::LifetimeNs(_) + | DefPathData::DesugaredAnonymousLifetime | DefPathData::OpaqueLifetime(_) | DefPathData::AnonAssocTy(..) => { bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data) diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs index bff5e9128cbf1..db35c988bf7fa 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs @@ -841,54 +841,32 @@ fn foo(&self) -> Self::T { String::new() } let param_env = tcx.param_env(body_owner_def_id); - match item { - hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. }) => { - // FIXME: account for `#![feature(specialization)]` - for item in &items[..] { - match item.kind { - hir::AssocItemKind::Type => { - // FIXME: account for returning some type in a trait fn impl that has - // an assoc type as a return type (#72076). - if let hir::Defaultness::Default { has_value: true } = - tcx.defaultness(item.id.owner_id) - { - let assoc_ty = tcx.type_of(item.id.owner_id).instantiate_identity(); - if self.infcx.can_eq(param_env, assoc_ty, found) { - diag.span_label( - item.span, - "associated type defaults can't be assumed inside the \ - trait defining them", - ); - return true; - } - } + if let DefKind::Trait | DefKind::Impl { .. } = tcx.def_kind(parent_id) { + let assoc_items = tcx.associated_items(parent_id); + // FIXME: account for `#![feature(specialization)]` + for assoc_item in assoc_items.in_definition_order() { + if assoc_item.is_type() + // FIXME: account for returning some type in a trait fn impl that has + // an assoc type as a return type (#72076). + && let hir::Defaultness::Default { has_value: true } = assoc_item.defaultness(tcx) + && let assoc_ty = tcx.type_of(assoc_item.def_id).instantiate_identity() + && self.infcx.can_eq(param_env, assoc_ty, found) + { + let msg = match assoc_item.container { + ty::AssocItemContainer::Trait => { + "associated type defaults can't be assumed inside the \ + trait defining them" } - _ => {} - } - } - } - hir::Node::Item(hir::Item { - kind: hir::ItemKind::Impl(hir::Impl { items, .. }), - .. - }) => { - for item in &items[..] { - if let hir::AssocItemKind::Type = item.kind { - let assoc_ty = tcx.type_of(item.id.owner_id).instantiate_identity(); - if let hir::Defaultness::Default { has_value: true } = - tcx.defaultness(item.id.owner_id) - && self.infcx.can_eq(param_env, assoc_ty, found) - { - diag.span_label( - item.span, - "associated type is `default` and may be overridden", - ); - return true; + ty::AssocItemContainer::Impl => { + "associated type is `default` and may be overridden" } - } + }; + diag.span_label(tcx.def_span(assoc_item.def_id), msg); + return true; } } - _ => {} } + false } diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs index 39f115ce0cd56..8a7dcb433dc02 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs @@ -355,7 +355,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { && self.tcx.trait_of_item(*item_id) == Some(*trait_id) && let None = self.tainted_by_errors() { - let (verb, noun) = match self.tcx.associated_item(item_id).kind { + let assoc_item = self.tcx.associated_item(item_id); + let (verb, noun) = match assoc_item.kind { ty::AssocKind::Const { .. } => ("refer to the", "constant"), ty::AssocKind::Fn { .. } => ("call", "function"), // This is already covered by E0223, but this following single match @@ -374,17 +375,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { ); err.code(E0790); - if let Some(local_def_id) = data.trait_ref.def_id.as_local() - && let hir::Node::Item(hir::Item { - kind: hir::ItemKind::Trait(_, _, trait_ident, _, _, trait_item_refs), - .. - }) = self.tcx.hir_node_by_def_id(local_def_id) - && let Some(method_ref) = trait_item_refs - .iter() - .find(|item_ref| item_ref.ident == *assoc_item_ident) - { + if item_id.is_local() { + let trait_ident = self.tcx.item_name(*trait_id); err.span_label( - method_ref.span, + self.tcx.def_span(*item_id), format!("`{trait_ident}::{assoc_item_ident}` defined here"), ); } diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index d4e6a23f0eb6b..fed9f254cdf83 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -288,9 +288,9 @@ fn extend_cause_with_original_assoc_item_obligation<'tcx>( && let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&projection_ty.def_id) && let Some(impl_item) = - items.iter().find(|item| item.id.owner_id.to_def_id() == impl_item_id) + items.iter().find(|item| item.owner_id.to_def_id() == impl_item_id) { - Some(tcx.hir_impl_item(impl_item.id).expect_type().span) + Some(tcx.hir_impl_item(*impl_item).expect_type().span) } else { None } diff --git a/compiler/rustc_ty_utils/src/assoc.rs b/compiler/rustc_ty_utils/src/assoc.rs index a65f9b347dc6d..648ced61e4df2 100644 --- a/compiler/rustc_ty_utils/src/assoc.rs +++ b/compiler/rustc_ty_utils/src/assoc.rs @@ -6,6 +6,8 @@ use rustc_hir::intravisit::{self, Visitor}; use rustc_middle::query::Providers; use rustc_middle::ty::{self, ImplTraitInTraitData, TyCtxt}; use rustc_middle::{bug, span_bug}; +use rustc_span::Ident; +use rustc_span::symbol::kw; pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { @@ -28,15 +30,15 @@ fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[DefId] { tcx.arena.alloc_from_iter( trait_item_refs .iter() - .map(|trait_item_ref| trait_item_ref.id.owner_id.to_def_id()) + .map(|trait_item_ref| trait_item_ref.owner_id.to_def_id()) .chain( trait_item_refs .iter() .filter(|trait_item_ref| { - matches!(trait_item_ref.kind, hir::AssocItemKind::Fn { .. }) + matches!(tcx.def_kind(trait_item_ref.owner_id), DefKind::AssocFn) }) .flat_map(|trait_item_ref| { - let trait_fn_def_id = trait_item_ref.id.owner_id.def_id.to_def_id(); + let trait_fn_def_id = trait_item_ref.owner_id.to_def_id(); tcx.associated_types_for_impl_traits_in_associated_fn( trait_fn_def_id, ) @@ -50,25 +52,23 @@ fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[DefId] { // create a corresponding associated item using // associated_types_for_impl_traits_in_associated_fn query. tcx.arena.alloc_from_iter( - impl_ - .items - .iter() - .map(|impl_item_ref| impl_item_ref.id.owner_id.to_def_id()) - .chain(impl_.of_trait.iter().flat_map(|_| { + impl_.items.iter().map(|impl_item_ref| impl_item_ref.owner_id.to_def_id()).chain( + impl_.of_trait.iter().flat_map(|_| { impl_ .items .iter() .filter(|impl_item_ref| { - matches!(impl_item_ref.kind, hir::AssocItemKind::Fn { .. }) + matches!(tcx.def_kind(impl_item_ref.owner_id), DefKind::AssocFn) }) .flat_map(|impl_item_ref| { - let impl_fn_def_id = impl_item_ref.id.owner_id.def_id.to_def_id(); + let impl_fn_def_id = impl_item_ref.owner_id.to_def_id(); tcx.associated_types_for_impl_traits_in_associated_fn( impl_fn_def_id, ) }) .copied() - })), + }), + ), ) } _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"), @@ -92,46 +92,33 @@ fn impl_item_implementor_ids(tcx: TyCtxt<'_>, impl_id: DefId) -> DefIdMap } fn associated_item(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AssocItem { - let id = tcx.local_def_id_to_hir_id(def_id); - let parent_def_id = tcx.hir_get_parent_item(id); - let parent_item = tcx.hir_expect_item(parent_def_id.def_id); - match parent_item.kind { - hir::ItemKind::Impl(impl_) => { - if let Some(impl_item_ref) = impl_.items.iter().find(|i| i.id.owner_id.def_id == def_id) - { - let assoc_item = associated_item_from_impl_item_ref(impl_item_ref); - debug_assert_eq!(assoc_item.def_id.expect_local(), def_id); - return assoc_item; - } - } - - hir::ItemKind::Trait(.., trait_item_refs) => { - if let Some(trait_item_ref) = - trait_item_refs.iter().find(|i| i.id.owner_id.def_id == def_id) - { - let assoc_item = associated_item_from_trait_item_ref(trait_item_ref); - debug_assert_eq!(assoc_item.def_id.expect_local(), def_id); - return assoc_item; - } - } - - _ => {} - } + let assoc_item = match tcx.hir_node_by_def_id(def_id) { + hir::Node::TraitItem(ti) => associated_item_from_trait_item(tcx, ti), + hir::Node::ImplItem(ii) => associated_item_from_impl_item(tcx, ii), + node => span_bug!(tcx.def_span(def_id), "impl item or item not found: {:?}", node,), + }; + debug_assert_eq!(assoc_item.def_id.expect_local(), def_id); + assoc_item +} - span_bug!( - parent_item.span, - "unexpected parent of trait or impl item or item not found: {:?}", - parent_item.kind - ) +fn fn_has_self_parameter(tcx: TyCtxt<'_>, owner_id: hir::OwnerId) -> bool { + matches!(tcx.fn_arg_idents(owner_id.def_id), [Some(Ident { name: kw::SelfLower, .. }), ..]) } -fn associated_item_from_trait_item_ref(trait_item_ref: &hir::TraitItemRef) -> ty::AssocItem { - let owner_id = trait_item_ref.id.owner_id; - let name = trait_item_ref.ident.name; - let kind = match trait_item_ref.kind { - hir::AssocItemKind::Const => ty::AssocKind::Const { name }, - hir::AssocItemKind::Fn { has_self } => ty::AssocKind::Fn { name, has_self }, - hir::AssocItemKind::Type => ty::AssocKind::Type { data: ty::AssocTypeData::Normal(name) }, +fn associated_item_from_trait_item( + tcx: TyCtxt<'_>, + trait_item: &hir::TraitItem<'_>, +) -> ty::AssocItem { + let owner_id = trait_item.owner_id; + let name = trait_item.ident.name; + let kind = match trait_item.kind { + hir::TraitItemKind::Const { .. } => ty::AssocKind::Const { name }, + hir::TraitItemKind::Fn { .. } => { + ty::AssocKind::Fn { name, has_self: fn_has_self_parameter(tcx, owner_id) } + } + hir::TraitItemKind::Type { .. } => { + ty::AssocKind::Type { data: ty::AssocTypeData::Normal(name) } + } }; ty::AssocItem { @@ -142,22 +129,27 @@ fn associated_item_from_trait_item_ref(trait_item_ref: &hir::TraitItemRef) -> ty } } -fn associated_item_from_impl_item_ref(impl_item_ref: &hir::ImplItemRef) -> ty::AssocItem { - let def_id = impl_item_ref.id.owner_id; - let name = impl_item_ref.ident.name; - let kind = match impl_item_ref.kind { - hir::AssocItemKind::Const => ty::AssocKind::Const { name }, - hir::AssocItemKind::Fn { has_self } => ty::AssocKind::Fn { name, has_self }, - hir::AssocItemKind::Type => ty::AssocKind::Type { data: ty::AssocTypeData::Normal(name) }, +fn associated_item_from_impl_item(tcx: TyCtxt<'_>, impl_item: &hir::ImplItem<'_>) -> ty::AssocItem { + let owner_id = impl_item.owner_id; + let name = impl_item.ident.name; + let kind = match impl_item.kind { + hir::ImplItemKind::Const { .. } => ty::AssocKind::Const { name }, + hir::ImplItemKind::Fn { .. } => { + ty::AssocKind::Fn { name, has_self: fn_has_self_parameter(tcx, owner_id) } + } + hir::ImplItemKind::Type { .. } => { + ty::AssocKind::Type { data: ty::AssocTypeData::Normal(name) } + } }; ty::AssocItem { kind, - def_id: def_id.to_def_id(), - trait_item_def_id: impl_item_ref.trait_item_def_id, + def_id: owner_id.to_def_id(), + trait_item_def_id: impl_item.trait_item_def_id, container: ty::AssocItemContainer::Impl, } } + struct RPITVisitor<'tcx> { tcx: TyCtxt<'tcx>, synthetics: Vec, diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 96199cb972a86..5cd6ab6b5e545 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -493,7 +493,7 @@ pub(crate) fn build_impl( impl_ .items .iter() - .map(|item| tcx.hir_impl_item(item.id)) + .map(|&item| tcx.hir_impl_item(item)) .filter(|item| { // Filter out impl items whose corresponding trait item has `doc(hidden)` // not to document such impl items. diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 5cd5c434521c0..8a16e9c37f320 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2859,7 +2859,7 @@ fn clean_maybe_renamed_item<'tcx>( ItemKind::Trait(_, _, _, generics, bounds, item_ids) => { let items = item_ids .iter() - .map(|ti| clean_trait_item(cx.tcx.hir_trait_item(ti.id), cx)) + .map(|&ti| clean_trait_item(cx.tcx.hir_trait_item(ti), cx)) .collect(); TraitItem(Box::new(Trait { @@ -2902,7 +2902,7 @@ fn clean_impl<'tcx>( let items = impl_ .items .iter() - .map(|ii| clean_impl_item(tcx.hir_impl_item(ii.id), cx)) + .map(|&ii| clean_impl_item(tcx.hir_impl_item(ii), cx)) .collect::>(); // If this impl block is an implementation of the Deref trait, then we diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 2889bfae7b000..2f06d5dadc721 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -439,8 +439,8 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { match item.kind { hir::ItemKind::ForeignMod { items, .. } => { - for item in items { - let item = tcx.hir_foreign_item(item.id); + for &item in items { + let item = tcx.hir_foreign_item(item); self.visit_foreign_item_inner(item, None, None); } } diff --git a/src/tools/clippy/clippy_lints/src/arbitrary_source_item_ordering.rs b/src/tools/clippy/clippy_lints/src/arbitrary_source_item_ordering.rs index b9ae9afe85100..3e41666c7026a 100644 --- a/src/tools/clippy/clippy_lints/src/arbitrary_source_item_ordering.rs +++ b/src/tools/clippy/clippy_lints/src/arbitrary_source_item_ordering.rs @@ -8,11 +8,13 @@ use clippy_utils::diagnostics::span_lint_and_note; use clippy_utils::is_cfg_test; use rustc_attr_data_structures::AttributeKind; use rustc_hir::{ - AssocItemKind, Attribute, FieldDef, HirId, ImplItemRef, IsAuto, Item, ItemKind, Mod, QPath, TraitItemRef, TyKind, + Attribute, FieldDef, HirId, IsAuto, ImplItemId, Item, ItemKind, Mod, OwnerId, QPath, TraitItemId, TyKind, Variant, VariantData, }; +use rustc_middle::ty::AssocKind; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::impl_lint_pass; +use rustc_span::Ident; declare_clippy_lint! { /// ### What it does @@ -194,22 +196,22 @@ impl ArbitrarySourceItemOrdering { } /// Produces a linting warning for incorrectly ordered impl items. - fn lint_impl_item(&self, cx: &T, item: &ImplItemRef, before_item: &ImplItemRef) { + fn lint_impl_item(&self, cx: &LateContext<'_>, item: ImplItemId, before_item: ImplItemId) { span_lint_and_note( cx, ARBITRARY_SOURCE_ITEM_ORDERING, - item.span, + cx.tcx.def_span(item.owner_id), format!( "incorrect ordering of impl items (defined order: {:?})", self.assoc_types_order ), - Some(before_item.span), - format!("should be placed before `{}`", before_item.ident.name), + Some(cx.tcx.def_span(before_item.owner_id)), + format!("should be placed before `{}`", cx.tcx.item_name(before_item.owner_id)), ); } /// Produces a linting warning for incorrectly ordered item members. - fn lint_member_name(cx: &T, ident: &rustc_span::Ident, before_ident: &rustc_span::Ident) { + fn lint_member_name(cx: &T, ident: Ident, before_ident: Ident) { span_lint_and_note( cx, ARBITRARY_SOURCE_ITEM_ORDERING, @@ -220,7 +222,7 @@ impl ArbitrarySourceItemOrdering { ); } - fn lint_member_item(cx: &T, item: &Item<'_>, before_item: &Item<'_>, msg: &'static str) { + fn lint_member_item(cx: &LateContext<'_>, item: &Item<'_>, before_item: &Item<'_>, msg: &'static str) { let span = if let Some(ident) = item.kind.ident() { ident.span } else { @@ -245,17 +247,17 @@ impl ArbitrarySourceItemOrdering { } /// Produces a linting warning for incorrectly ordered trait items. - fn lint_trait_item(&self, cx: &T, item: &TraitItemRef, before_item: &TraitItemRef) { + fn lint_trait_item(&self, cx: &LateContext<'_>, item: TraitItemId, before_item: TraitItemId) { span_lint_and_note( cx, ARBITRARY_SOURCE_ITEM_ORDERING, - item.span, + cx.tcx.def_span(item.owner_id), format!( "incorrect ordering of trait items (defined order: {:?})", self.assoc_types_order ), - Some(before_item.span), - format!("should be placed before `{}`", before_item.ident.name), + Some(cx.tcx.def_span(before_item.owner_id)), + format!("should be placed before `{}`", cx.tcx.item_name(before_item.owner_id)), ); } } @@ -283,7 +285,7 @@ impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering { && cur_v.ident.name.as_str() > variant.ident.name.as_str() && cur_v.span != variant.span { - Self::lint_member_name(cx, &variant.ident, &cur_v.ident); + Self::lint_member_name(cx, variant.ident, cur_v.ident); } cur_v = Some(variant); } @@ -299,7 +301,7 @@ impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering { && cur_f.ident.name.as_str() > field.ident.name.as_str() && cur_f.span != field.span { - Self::lint_member_name(cx, &field.ident, &cur_f.ident); + Self::lint_member_name(cx, field.ident, cur_f.ident); } cur_f = Some(field); } @@ -307,49 +309,53 @@ impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering { ItemKind::Trait(is_auto, _safety, _ident, _generics, _generic_bounds, item_ref) if self.enable_ordering_for_trait && *is_auto == IsAuto::No => { - let mut cur_t: Option<&TraitItemRef> = None; + let mut cur_t: Option<(TraitItemId, Ident)> = None; - for item in *item_ref { - if item.span.in_external_macro(cx.sess().source_map()) { + for &item in *item_ref { + let span = cx.tcx.def_span(item.owner_id); + let ident = cx.tcx.item_ident(item.owner_id); + if span.in_external_macro(cx.sess().source_map()) { continue; } - if let Some(cur_t) = cur_t { - let cur_t_kind = convert_assoc_item_kind(cur_t.kind); + if let Some((cur_t, cur_ident)) = cur_t { + let cur_t_kind = convert_assoc_item_kind(cx, cur_t.owner_id); let cur_t_kind_index = self.assoc_types_order.index_of(&cur_t_kind); - let item_kind = convert_assoc_item_kind(item.kind); + let item_kind = convert_assoc_item_kind(cx, item.owner_id); let item_kind_index = self.assoc_types_order.index_of(&item_kind); - if cur_t_kind == item_kind && cur_t.ident.name.as_str() > item.ident.name.as_str() { - Self::lint_member_name(cx, &item.ident, &cur_t.ident); + if cur_t_kind == item_kind && cur_ident.name.as_str() > ident.name.as_str() { + Self::lint_member_name(cx, ident, cur_ident); } else if cur_t_kind_index > item_kind_index { self.lint_trait_item(cx, item, cur_t); } } - cur_t = Some(item); + cur_t = Some((item, ident)); } }, ItemKind::Impl(trait_impl) if self.enable_ordering_for_impl => { - let mut cur_t: Option<&ImplItemRef> = None; + let mut cur_t: Option<(ImplItemId, Ident)> = None; - for item in trait_impl.items { - if item.span.in_external_macro(cx.sess().source_map()) { + for &item in trait_impl.items { + let span = cx.tcx.def_span(item.owner_id); + let ident = cx.tcx.item_ident(item.owner_id); + if span.in_external_macro(cx.sess().source_map()) { continue; } - if let Some(cur_t) = cur_t { - let cur_t_kind = convert_assoc_item_kind(cur_t.kind); + if let Some((cur_t, cur_ident)) = cur_t { + let cur_t_kind = convert_assoc_item_kind(cx, cur_t.owner_id); let cur_t_kind_index = self.assoc_types_order.index_of(&cur_t_kind); - let item_kind = convert_assoc_item_kind(item.kind); + let item_kind = convert_assoc_item_kind(cx, item.owner_id); let item_kind_index = self.assoc_types_order.index_of(&item_kind); - if cur_t_kind == item_kind && cur_t.ident.name.as_str() > item.ident.name.as_str() { - Self::lint_member_name(cx, &item.ident, &cur_t.ident); + if cur_t_kind == item_kind && cur_ident.name.as_str() > ident.name.as_str() { + Self::lint_member_name(cx, ident, cur_ident); } else if cur_t_kind_index > item_kind_index { self.lint_impl_item(cx, item, cur_t); } } - cur_t = Some(item); + cur_t = Some((item, ident)); } }, _ => {}, // Catch-all for `ItemKinds` that don't have fields. @@ -458,18 +464,19 @@ impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering { } } -/// Converts a [`rustc_hir::AssocItemKind`] to a -/// [`SourceItemOrderingTraitAssocItemKind`]. +/// Converts a [`ty::AssocKind`] to a [`SourceItemOrderingTraitAssocItemKind`]. /// /// This is implemented here because `rustc_hir` is not a dependency of /// `clippy_config`. -fn convert_assoc_item_kind(value: AssocItemKind) -> SourceItemOrderingTraitAssocItemKind { +fn convert_assoc_item_kind(cx: &LateContext<'_>, owner_id: OwnerId) -> SourceItemOrderingTraitAssocItemKind { + let kind = cx.tcx.associated_item(owner_id.def_id).kind; + #[allow(clippy::enum_glob_use)] // Very local glob use for legibility. use SourceItemOrderingTraitAssocItemKind::*; - match value { - AssocItemKind::Const => Const, - AssocItemKind::Type => Type, - AssocItemKind::Fn { .. } => Fn, + match kind { + AssocKind::Const{..} => Const, + AssocKind::Type {..}=> Type, + AssocKind::Fn { .. } => Fn, } } diff --git a/src/tools/clippy/clippy_lints/src/derivable_impls.rs b/src/tools/clippy/clippy_lints/src/derivable_impls.rs index 10331b3855b84..0a481ddcd12e4 100644 --- a/src/tools/clippy/clippy_lints/src/derivable_impls.rs +++ b/src/tools/clippy/clippy_lints/src/derivable_impls.rs @@ -192,7 +192,7 @@ impl<'tcx> LateLintPass<'tcx> for DerivableImpls { && !item.span.from_expansion() && let Some(def_id) = trait_ref.trait_def_id() && cx.tcx.is_diagnostic_item(sym::Default, def_id) - && let impl_item_hir = child.id.hir_id() + && let impl_item_hir = child.hir_id() && let Node::ImplItem(impl_item) = cx.tcx.hir_node(impl_item_hir) && let ImplItemKind::Fn(_, b) = &impl_item.kind && let Body { value: func_expr, .. } = cx.tcx.hir_body(*b) diff --git a/src/tools/clippy/clippy_lints/src/empty_drop.rs b/src/tools/clippy/clippy_lints/src/empty_drop.rs index d557a36c7ac2d..4e948701da4ff 100644 --- a/src/tools/clippy/clippy_lints/src/empty_drop.rs +++ b/src/tools/clippy/clippy_lints/src/empty_drop.rs @@ -41,7 +41,7 @@ impl LateLintPass<'_> for EmptyDrop { .. }) = item.kind && trait_ref.trait_def_id() == cx.tcx.lang_items().drop_trait() - && let impl_item_hir = child.id.hir_id() + && let impl_item_hir = child.hir_id() && let Node::ImplItem(impl_item) = cx.tcx.hir_node(impl_item_hir) && let ImplItemKind::Fn(_, b) = &impl_item.kind && let Body { value: func_expr, .. } = cx.tcx.hir_body(*b) diff --git a/src/tools/clippy/clippy_lints/src/escape.rs b/src/tools/clippy/clippy_lints/src/escape.rs index 2cb3b32babe89..db2fea1aae95d 100644 --- a/src/tools/clippy/clippy_lints/src/escape.rs +++ b/src/tools/clippy/clippy_lints/src/escape.rs @@ -1,7 +1,8 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_hir; use rustc_abi::ExternAbi; -use rustc_hir::{AssocItemKind, Body, FnDecl, HirId, HirIdSet, Impl, ItemKind, Node, Pat, PatKind, intravisit}; +use rustc_hir::{Body, FnDecl, HirId, HirIdSet, Node, Pat, PatKind, intravisit}; +use rustc_hir::def::DefKind; use rustc_hir_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::mir::FakeReadCause; @@ -84,23 +85,18 @@ impl<'tcx> LateLintPass<'tcx> for BoxedLocal { .def_id; let mut trait_self_ty = None; - if let Node::Item(item) = cx.tcx.hir_node_by_def_id(parent_id) { + match cx.tcx.def_kind(parent_id) { // If the method is an impl for a trait, don't warn. - if let ItemKind::Impl(Impl { of_trait: Some(_), .. }) = item.kind { - return; + DefKind::Impl { of_trait: true } => { + return } // find `self` ty for this trait if relevant - if let ItemKind::Trait(_, _, _, _, _, items) = item.kind { - for trait_item in items { - if trait_item.id.owner_id.def_id == fn_def_id - // be sure we have `self` parameter in this function - && trait_item.kind == (AssocItemKind::Fn { has_self: true }) - { - trait_self_ty = Some(TraitRef::identity(cx.tcx, trait_item.id.owner_id.to_def_id()).self_ty()); - } - } + DefKind::Trait => { + trait_self_ty = Some(TraitRef::identity(cx.tcx, parent_id.to_def_id()).self_ty()); } + + _ => {} } let mut v = EscapeDelegate { diff --git a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs index 68d0cd19c8a69..552cd721f4ef9 100644 --- a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs +++ b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs @@ -52,20 +52,20 @@ declare_lint_pass!(FallibleImplFrom => [FALLIBLE_IMPL_FROM]); impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) { // check for `impl From for ..` - if let hir::ItemKind::Impl(impl_) = &item.kind + if let hir::ItemKind::Impl(_) = &item.kind && let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.owner_id) && cx .tcx .is_diagnostic_item(sym::From, impl_trait_ref.skip_binder().def_id) { - lint_impl_body(cx, item.span, impl_.items); + lint_impl_body(cx, item.owner_id, item.span); } } } -fn lint_impl_body(cx: &LateContext<'_>, impl_span: Span, impl_items: &[hir::ImplItemRef]) { +fn lint_impl_body(cx: &LateContext<'_>, item_def_id: hir::OwnerId, impl_span: Span) { use rustc_hir::intravisit::{self, Visitor}; - use rustc_hir::{Expr, ImplItemKind}; + use rustc_hir::Expr; struct FindPanicUnwrap<'a, 'tcx> { lcx: &'a LateContext<'tcx>, @@ -96,35 +96,35 @@ fn lint_impl_body(cx: &LateContext<'_>, impl_span: Span, impl_items: &[hir::Impl } } - for impl_item in impl_items { - if impl_item.ident.name == sym::from - && let ImplItemKind::Fn(_, body_id) = cx.tcx.hir_impl_item(impl_item.id).kind - { - // check the body for `begin_panic` or `unwrap` - let body = cx.tcx.hir_body(body_id); - let mut fpu = FindPanicUnwrap { - lcx: cx, - typeck_results: cx.tcx.typeck(impl_item.id.owner_id.def_id), - result: Vec::new(), - }; - fpu.visit_expr(body.value); + for impl_item in cx.tcx.associated_items(item_def_id) + .filter_by_name_unhygienic_and_kind(sym::from, ty::AssocTag::Fn) + { + let impl_item_def_id= impl_item.def_id.expect_local(); - // if we've found one, lint - if !fpu.result.is_empty() { - span_lint_and_then( - cx, - FALLIBLE_IMPL_FROM, - impl_span, - "consider implementing `TryFrom` instead", - move |diag| { - diag.help( - "`From` is intended for infallible conversions only. \ - Use `TryFrom` if there's a possibility for the conversion to fail", - ); - diag.span_note(fpu.result, "potential failure(s)"); - }, - ); - } + // check the body for `begin_panic` or `unwrap` + let body = cx.tcx.hir_body_owned_by(impl_item_def_id); + let mut fpu = FindPanicUnwrap { + lcx: cx, + typeck_results: cx.tcx.typeck(impl_item_def_id), + result: Vec::new(), + }; + fpu.visit_expr(body.value); + + // if we've found one, lint + if !fpu.result.is_empty() { + span_lint_and_then( + cx, + FALLIBLE_IMPL_FROM, + impl_span, + "consider implementing `TryFrom` instead", + move |diag| { + diag.help( + "`From` is intended for infallible conversions only. \ + Use `TryFrom` if there's a possibility for the conversion to fail", + ); + diag.span_note(fpu.result, "potential failure(s)"); + }, + ); } } } diff --git a/src/tools/clippy/clippy_lints/src/from_over_into.rs b/src/tools/clippy/clippy_lints/src/from_over_into.rs index be887b03ae4b6..85b40ba7419b3 100644 --- a/src/tools/clippy/clippy_lints/src/from_over_into.rs +++ b/src/tools/clippy/clippy_lints/src/from_over_into.rs @@ -9,7 +9,7 @@ use clippy_utils::source::SpanRangeExt; use rustc_errors::Applicability; use rustc_hir::intravisit::{Visitor, walk_path}; use rustc_hir::{ - FnRetTy, GenericArg, GenericArgs, HirId, Impl, ImplItemKind, ImplItemRef, Item, ItemKind, PatKind, Path, + FnRetTy, GenericArg, GenericArgs, HirId, Impl, ImplItemKind, ImplItemId, Item, ItemKind, PatKind, Path, PathSegment, Ty, TyKind, }; use rustc_lint::{LateContext, LateLintPass}; @@ -102,7 +102,7 @@ impl<'tcx> LateLintPass<'tcx> for FromOverInto { middle_trait_ref.self_ty() ); if let Some(suggestions) = - convert_to_from(cx, into_trait_seg, target_ty.as_unambig_ty(), self_ty, impl_item_ref) + convert_to_from(cx, into_trait_seg, target_ty.as_unambig_ty(), self_ty, *impl_item_ref) { diag.multipart_suggestion(message, suggestions, Applicability::MachineApplicable); } else { @@ -164,14 +164,14 @@ fn convert_to_from( into_trait_seg: &PathSegment<'_>, target_ty: &Ty<'_>, self_ty: &Ty<'_>, - impl_item_ref: &ImplItemRef, + impl_item_ref: ImplItemId, ) -> Option> { if !target_ty.find_self_aliases().is_empty() { // It's tricky to expand self-aliases correctly, we'll ignore it to not cause a // bad suggestion/fix. return None; } - let impl_item = cx.tcx.hir_impl_item(impl_item_ref.id); + let impl_item = cx.tcx.hir_impl_item(impl_item_ref); let ImplItemKind::Fn(ref sig, body_id) = impl_item.kind else { return None; }; diff --git a/src/tools/clippy/clippy_lints/src/functions/renamed_function_params.rs b/src/tools/clippy/clippy_lints/src/functions/renamed_function_params.rs index 2d22bb157a93c..0d6191f2c9715 100644 --- a/src/tools/clippy/clippy_lints/src/functions/renamed_function_params.rs +++ b/src/tools/clippy/clippy_lints/src/functions/renamed_function_params.rs @@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use rustc_errors::{Applicability, MultiSpan}; use rustc_hir::def_id::{DefId, DefIdSet}; use rustc_hir::hir_id::OwnerId; -use rustc_hir::{Impl, ImplItem, ImplItemKind, ImplItemRef, ItemKind, Node, TraitRef}; +use rustc_hir::{Impl, ImplItem, ImplItemKind, ItemKind, Node, TraitRef}; use rustc_lint::LateContext; use rustc_span::Span; use rustc_span::symbol::{Ident, kw}; @@ -15,11 +15,10 @@ pub(super) fn check_impl_item(cx: &LateContext<'_>, item: &ImplItem<'_>, ignored && let parent_node = cx.tcx.parent_hir_node(item.hir_id()) && let Node::Item(parent_item) = parent_node && let ItemKind::Impl(Impl { - items, of_trait: Some(trait_ref), .. }) = &parent_item.kind - && let Some(did) = trait_item_def_id_of_impl(items, item.owner_id) + && let Some(did) = trait_item_def_id_of_impl(cx, item.owner_id) && !is_from_ignored_trait(trait_ref, ignored_traits) { let mut param_idents_iter = cx.tcx.hir_body_param_idents(body_id); @@ -93,14 +92,8 @@ impl RenamedFnArgs { } /// Get the [`trait_item_def_id`](ImplItemRef::trait_item_def_id) of a relevant impl item. -fn trait_item_def_id_of_impl(items: &[ImplItemRef], target: OwnerId) -> Option { - items.iter().find_map(|item| { - if item.id.owner_id == target { - item.trait_item_def_id - } else { - None - } - }) +fn trait_item_def_id_of_impl(cx: &LateContext<'_>, target: OwnerId) -> Option { + cx.tcx.associated_item(target).trait_item_def_id } fn is_from_ignored_trait(of_trait: &TraitRef<'_>, ignored_traits: &DefIdSet) -> bool { diff --git a/src/tools/clippy/clippy_lints/src/implicit_hasher.rs b/src/tools/clippy/clippy_lints/src/implicit_hasher.rs index cab7a9fb70990..b3c90f364e834 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_hasher.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_hasher.rs @@ -130,7 +130,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitHasher { }); let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target); - for item in impl_.items.iter().map(|item| cx.tcx.hir_impl_item(item.id)) { + for item in impl_.items.iter().map(|&item| cx.tcx.hir_impl_item(item)) { ctr_vis.visit_impl_item(item); } diff --git a/src/tools/clippy/clippy_lints/src/infallible_try_from.rs b/src/tools/clippy/clippy_lints/src/infallible_try_from.rs index b54c289fa7e13..e79fcec6e6acf 100644 --- a/src/tools/clippy/clippy_lints/src/infallible_try_from.rs +++ b/src/tools/clippy/clippy_lints/src/infallible_try_from.rs @@ -1,8 +1,9 @@ use clippy_utils::diagnostics::span_lint; use clippy_utils::sym; use rustc_errors::MultiSpan; -use rustc_hir::{AssocItemKind, Item, ItemKind}; +use rustc_hir::{Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; +use rustc_middle::ty::AssocTag; use rustc_session::declare_lint_pass; declare_clippy_lint! { @@ -51,25 +52,23 @@ impl<'tcx> LateLintPass<'tcx> for InfallibleTryFrom { if !cx.tcx.is_diagnostic_item(sym::TryFrom, trait_def_id) { return; } - for ii in imp.items { - if ii.kind == AssocItemKind::Type { - let ii = cx.tcx.hir_impl_item(ii.id); - if ii.ident.name != sym::Error { - continue; - } - let ii_ty = ii.expect_type(); - let ii_ty_span = ii_ty.span; - let ii_ty = clippy_utils::ty::ty_from_hir_ty(cx, ii_ty); - if !ii_ty.is_inhabited_from(cx.tcx, ii.owner_id.to_def_id(), cx.typing_env()) { - let mut span = MultiSpan::from_span(cx.tcx.def_span(item.owner_id.to_def_id())); - span.push_span_label(ii_ty_span, "infallible error type"); - span_lint( - cx, - INFALLIBLE_TRY_FROM, - span, - "infallible TryFrom impl; consider implementing From, instead", - ); - } + for ii in cx.tcx.associated_items(item.owner_id.def_id) + .filter_by_name_unhygienic_and_kind(sym::Error, AssocTag::Type) + { + let ii_ty = cx.tcx.type_of(ii.def_id).instantiate_identity(); + if !ii_ty.is_inhabited_from(cx.tcx, ii.def_id, cx.typing_env()) { + let mut span = MultiSpan::from_span(cx.tcx.def_span(item.owner_id.to_def_id())); + let ii_ty_span = cx.tcx.hir_node_by_def_id(ii.def_id.expect_local()) + .expect_impl_item() + .expect_type() + .span; + span.push_span_label(ii_ty_span, "infallible error type"); + span_lint( + cx, + INFALLIBLE_TRY_FROM, + span, + "infallible TryFrom impl; consider implementing From, instead", + ); } } } diff --git a/src/tools/clippy/clippy_lints/src/iter_without_into_iter.rs b/src/tools/clippy/clippy_lints/src/iter_without_into_iter.rs index 900b20aa9cfb7..03038f0ab49c9 100644 --- a/src/tools/clippy/clippy_lints/src/iter_without_into_iter.rs +++ b/src/tools/clippy/clippy_lints/src/iter_without_into_iter.rs @@ -139,13 +139,12 @@ impl LateLintPass<'_> for IterWithoutIntoIter { // We can't check inherent impls for slices, but we know that they have an `iter(_mut)` method ty.peel_refs().is_slice() || get_adt_inherent_method(cx, ty, expected_method_name).is_some() }) - && let Some(iter_assoc_span) = imp.items.iter().find_map(|item| { - if item.ident.name == sym::IntoIter { - Some(cx.tcx.hir_impl_item(item.id).expect_type().span) - } else { - None - } - }) + && let Some(iter_assoc_span) = cx.tcx.associated_items(item.owner_id) + .filter_by_name_unhygienic_and_kind(sym::IntoIter, ty::AssocTag::Type) + .next() + .map(|assoc_item| { + cx.tcx.hir_node_by_def_id(assoc_item.def_id.expect_local()).expect_impl_item().expect_type().span + }) && is_ty_exported(cx, ty) { span_lint_and_then( diff --git a/src/tools/clippy/clippy_lints/src/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs index aded31971cec0..d32017a8b4144 100644 --- a/src/tools/clippy/clippy_lints/src/len_zero.rs +++ b/src/tools/clippy/clippy_lints/src/len_zero.rs @@ -10,14 +10,15 @@ use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::def_id::{DefId, DefIdSet}; use rustc_hir::{ - AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, GenericArg, GenericBound, HirId, ImplItem, ImplItemKind, + BinOpKind, Expr, ExprKind, FnRetTy, GenericArg, GenericBound, HirId, ImplItem, ImplItemKind, ImplicitSelfKind, Item, ItemKind, Mutability, Node, OpaqueTyOrigin, PatExprKind, PatKind, PathSegment, PrimTy, - QPath, TraitItemRef, TyKind, + QPath, TraitItemId, TyKind, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, FnSig, Ty}; use rustc_session::declare_lint_pass; use rustc_span::source_map::Spanned; +use rustc_span::symbol::kw; use rustc_span::{Ident, Span, Symbol}; use rustc_trait_selection::traits::supertrait_def_ids; @@ -264,22 +265,13 @@ fn span_without_enclosing_paren(cx: &LateContext<'_>, span: Span) -> Span { } } -fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, ident: Ident, trait_items: &[TraitItemRef]) { - fn is_named_self(cx: &LateContext<'_>, item: &TraitItemRef, name: Symbol) -> bool { - item.ident.name == name - && if let AssocItemKind::Fn { has_self } = item.kind { - has_self && { - cx.tcx - .fn_sig(item.id.owner_id) - .skip_binder() - .inputs() - .skip_binder() - .len() - == 1 - } - } else { - false - } +fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, ident: Ident, trait_items: &[TraitItemId]) { + fn is_named_self(cx: &LateContext<'_>, item: &TraitItemId, name: Symbol) -> bool { + cx.tcx.item_name(item.owner_id) == name + && matches!( + cx.tcx.fn_arg_idents(item.owner_id), + [Some(Ident { name: kw::SelfLower, .. })], + ) } // fill the set with current and super traits diff --git a/src/tools/clippy/clippy_lints/src/lifetimes.rs b/src/tools/clippy/clippy_lints/src/lifetimes.rs index 8fe0c9d60f961..e308577e7f87f 100644 --- a/src/tools/clippy/clippy_lints/src/lifetimes.rs +++ b/src/tools/clippy/clippy_lints/src/lifetimes.rs @@ -716,7 +716,7 @@ fn report_extra_impl_lifetimes<'tcx>(cx: &LateContext<'tcx>, impl_: &'tcx Impl<' walk_trait_ref(&mut checker, trait_ref); } walk_unambig_ty(&mut checker, impl_.self_ty); - for item in impl_.items { + for &item in impl_.items { walk_impl_item_ref(&mut checker, item); } diff --git a/src/tools/clippy/clippy_lints/src/missing_fields_in_debug.rs b/src/tools/clippy/clippy_lints/src/missing_fields_in_debug.rs index d4d33029dbdb1..760ecf0758921 100644 --- a/src/tools/clippy/clippy_lints/src/missing_fields_in_debug.rs +++ b/src/tools/clippy/clippy_lints/src/missing_fields_in_debug.rs @@ -8,7 +8,7 @@ use rustc_ast::LitKind; use rustc_data_structures::fx::FxHashSet; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{ - Block, Expr, ExprKind, Impl, ImplItem, ImplItemKind, Item, ItemKind, LangItem, Node, QPath, TyKind, VariantData, + Block, Expr, ExprKind, Impl, Item, ItemKind, LangItem, Node, QPath, TyKind, VariantData, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{Ty, TypeckResults}; @@ -200,7 +200,7 @@ fn check_struct<'tcx>( impl<'tcx> LateLintPass<'tcx> for MissingFieldsInDebug { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) { // is this an `impl Debug for X` block? - if let ItemKind::Impl(Impl { of_trait: Some(trait_ref), self_ty, items, .. }) = item.kind + if let ItemKind::Impl(Impl { of_trait: Some(trait_ref), self_ty, .. }) = item.kind && let Res::Def(DefKind::Trait, trait_def_id) = trait_ref.path.res && let TyKind::Path(QPath::Resolved(_, self_path)) = &self_ty.kind // make sure that the self type is either a struct, an enum or a union @@ -212,9 +212,8 @@ impl<'tcx> LateLintPass<'tcx> for MissingFieldsInDebug { && !cx.tcx.is_automatically_derived(item.owner_id.to_def_id()) && !item.span.from_expansion() // find `Debug::fmt` function - && let Some(fmt_item) = items.iter().find(|i| i.ident.name == sym::fmt) - && let ImplItem { kind: ImplItemKind::Fn(_, body_id), .. } = cx.tcx.hir_impl_item(fmt_item.id) - && let body = cx.tcx.hir_body(*body_id) + && let Some(fmt_item) = cx.tcx.associated_items(item.owner_id).filter_by_name_unhygienic(sym::fmt).next() + && let body = cx.tcx.hir_body_owned_by(fmt_item.def_id.expect_local()) && let ExprKind::Block(block, _) = body.value.kind // inspect `self` && let self_ty = cx.tcx.type_of(self_path_did).skip_binder().peel_refs() @@ -222,7 +221,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingFieldsInDebug { && let Some(self_def_id) = self_adt.did().as_local() && let Node::Item(self_item) = cx.tcx.hir_node_by_def_id(self_def_id) // NB: can't call cx.typeck_results() as we are not in a body - && let typeck_results = cx.tcx.typeck_body(*body_id) + && let typeck_results = cx.tcx.typeck_body(body.id()) && should_lint(cx, typeck_results, block) // we intentionally only lint structs, see lint description && let ItemKind::Struct(_, _, data) = &self_item.kind diff --git a/src/tools/clippy/clippy_lints/src/missing_inline.rs b/src/tools/clippy/clippy_lints/src/missing_inline.rs index 25c95d2343633..329f719343756 100644 --- a/src/tools/clippy/clippy_lints/src/missing_inline.rs +++ b/src/tools/clippy/clippy_lints/src/missing_inline.rs @@ -104,16 +104,16 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { hir::ItemKind::Trait(ref _is_auto, ref _unsafe, _ident, _generics, _bounds, trait_items) => { // note: we need to check if the trait is exported so we can't use // `LateLintPass::check_trait_item` here. - for tit in trait_items { - let tit_ = cx.tcx.hir_trait_item(tit.id); + for &tit in trait_items { + let tit_ = cx.tcx.hir_trait_item(tit); match tit_.kind { hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => {}, hir::TraitItemKind::Fn(..) => { - if cx.tcx.defaultness(tit.id.owner_id).has_value() { + if cx.tcx.defaultness(tit.owner_id).has_value() { // trait method with default body needs inline in case // an impl is not provided let desc = "a default trait method"; - let item = cx.tcx.hir_trait_item(tit.id); + let item = cx.tcx.hir_trait_item(tit); let attrs = cx.tcx.hir_attrs(item.hir_id()); check_missing_inline_attrs(cx, attrs, item.span, desc); } diff --git a/src/tools/clippy/clippy_lints/src/missing_trait_methods.rs b/src/tools/clippy/clippy_lints/src/missing_trait_methods.rs index e266c36b6e734..fa61d0fa11afc 100644 --- a/src/tools/clippy/clippy_lints/src/missing_trait_methods.rs +++ b/src/tools/clippy/clippy_lints/src/missing_trait_methods.rs @@ -61,15 +61,14 @@ impl<'tcx> LateLintPass<'tcx> for MissingTraitMethods { if !is_lint_allowed(cx, MISSING_TRAIT_METHODS, item.hir_id()) && span_is_local(item.span) && let ItemKind::Impl(Impl { - items, of_trait: Some(trait_ref), .. }) = item.kind && let Some(trait_id) = trait_ref.trait_def_id() { - let trait_item_ids: DefIdSet = items - .iter() - .filter_map(|impl_item| impl_item.trait_item_def_id) + let trait_item_ids: DefIdSet = cx.tcx.associated_items(item.owner_id) + .in_definition_order() + .filter_map(|assoc_item| assoc_item.trait_item_def_id) .collect(); for assoc in cx diff --git a/src/tools/clippy/clippy_lints/src/new_without_default.rs b/src/tools/clippy/clippy_lints/src/new_without_default.rs index 4b73a4455f55b..3b86f1d1f593c 100644 --- a/src/tools/clippy/clippy_lints/src/new_without_default.rs +++ b/src/tools/clippy/clippy_lints/src/new_without_default.rs @@ -6,6 +6,7 @@ use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::HirIdSet; use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_middle::ty::AssocKind; use rustc_session::impl_lint_pass; use rustc_span::sym; @@ -61,18 +62,18 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { of_trait: None, generics, self_ty: impl_self_ty, - items, .. }) = item.kind { - for assoc_item in *items { - if assoc_item.kind == (hir::AssocItemKind::Fn { has_self: false }) { - let impl_item = cx.tcx.hir_impl_item(assoc_item.id); + for assoc_item in cx.tcx.associated_items(item.owner_id.def_id) + .filter_by_name_unhygienic(sym::new) + { + if let AssocKind::Fn { has_self: false, .. } = assoc_item.kind { + let impl_item = cx.tcx.hir_node_by_def_id(assoc_item.def_id.expect_local()).expect_impl_item(); if impl_item.span.in_external_macro(cx.sess().source_map()) { return; } if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind { - let name = impl_item.ident.name; let id = impl_item.owner_id; if sig.header.is_unsafe() { // can't be implemented for unsafe new @@ -88,11 +89,9 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { return; } if sig.decl.inputs.is_empty() - && name == sym::new && cx.effective_visibilities.is_reachable(impl_item.owner_id.def_id) - && let self_def_id = cx.tcx.hir_get_parent_item(id.into()) - && let self_ty = cx.tcx.type_of(self_def_id).instantiate_identity() - && self_ty == return_ty(cx, id) + && let self_ty = cx.tcx.type_of(item.owner_id).instantiate_identity() + && self_ty == return_ty(cx, impl_item.owner_id) && let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default) { if self.impling_types.is_none() { @@ -111,7 +110,7 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { // Check if a Default implementation exists for the Self type, regardless of // generics if let Some(ref impling_types) = self.impling_types - && let self_def = cx.tcx.type_of(self_def_id).instantiate_identity() + && let self_def = cx.tcx.type_of(item.owner_id).instantiate_identity() && let Some(self_def) = self_def.ty_adt_def() && let Some(self_local_did) = self_def.did().as_local() && let self_id = cx.tcx.local_def_id_to_hir_id(self_local_did) diff --git a/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs b/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs index 8eaf65e63065e..301b2cd4bf2fc 100644 --- a/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs +++ b/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs @@ -43,12 +43,12 @@ impl<'tcx> LateLintPass<'tcx> for PartialEqNeImpl { && trait_ref.path.res.def_id() == eq_trait { for impl_item in *impl_items { - if impl_item.ident.name == sym::ne { + if cx.tcx.item_name(impl_item.owner_id) == sym::ne { span_lint_hir( cx, PARTIALEQ_NE_IMPL, - impl_item.id.hir_id(), - impl_item.span, + impl_item.hir_id(), + cx.tcx.def_span(impl_item.owner_id), "re-implementing `PartialEq::ne` is unnecessary", ); } diff --git a/src/tools/clippy/clippy_lints/src/same_name_method.rs b/src/tools/clippy/clippy_lints/src/same_name_method.rs index 226e8ff6adbf5..85fde780e6819 100644 --- a/src/tools/clippy/clippy_lints/src/same_name_method.rs +++ b/src/tools/clippy/clippy_lints/src/same_name_method.rs @@ -3,7 +3,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{HirId, Impl, ItemKind, Node, Path, QPath, TraitRef, TyKind}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::AssocItem; +use rustc_middle::ty::{AssocKind, AssocItem}; use rustc_session::declare_lint_pass; use rustc_span::Span; use rustc_span::symbol::Symbol; @@ -54,7 +54,6 @@ impl<'tcx> LateLintPass<'tcx> for SameNameMethod { if matches!(cx.tcx.def_kind(id.owner_id), DefKind::Impl { .. }) && let item = cx.tcx.hir_item(id) && let ItemKind::Impl(Impl { - items, of_trait, self_ty, .. @@ -115,13 +114,11 @@ impl<'tcx> LateLintPass<'tcx> for SameNameMethod { } }; - for impl_item_ref in (*items) - .iter() - .filter(|impl_item_ref| matches!(impl_item_ref.kind, rustc_hir::AssocItemKind::Fn { .. })) - { - let method_name = impl_item_ref.ident.name; - methods_in_trait.remove(&method_name); - check_trait_method(method_name, impl_item_ref.span); + for assoc_item in cx.tcx.associated_items(id.owner_id).in_definition_order() { + if let AssocKind::Fn { name, .. } = assoc_item.kind { + methods_in_trait.remove(&name); + check_trait_method(name, cx.tcx.def_span(assoc_item.def_id)); + } } for method_name in methods_in_trait { @@ -129,14 +126,11 @@ impl<'tcx> LateLintPass<'tcx> for SameNameMethod { } }, None => { - for impl_item_ref in (*items) - .iter() - .filter(|impl_item_ref| matches!(impl_item_ref.kind, rustc_hir::AssocItemKind::Fn { .. })) - { - let method_name = impl_item_ref.ident.name; - let impl_span = impl_item_ref.span; - let hir_id = impl_item_ref.id.hir_id(); - if let Some(trait_spans) = existing_name.trait_methods.get(&method_name) { + for assoc_item in cx.tcx.associated_items(id.owner_id).in_definition_order() { + let AssocKind::Fn { name, .. } = assoc_item.kind else { continue }; + let impl_span = cx.tcx.def_span(assoc_item.def_id); + let hir_id = cx.tcx.local_def_id_to_hir_id(assoc_item.def_id.expect_local()); + if let Some(trait_spans) = existing_name.trait_methods.get(&name) { span_lint_hir_and_then( cx, SAME_NAME_METHOD, @@ -148,12 +142,12 @@ impl<'tcx> LateLintPass<'tcx> for SameNameMethod { // iterate on trait_spans? diag.span_note( trait_spans[0], - format!("existing `{method_name}` defined here"), + format!("existing `{name}` defined here"), ); }, ); } - existing_name.impl_methods.insert(method_name, (impl_span, hir_id)); + existing_name.impl_methods.insert(name, (impl_span, hir_id)); } }, } diff --git a/src/tools/clippy/clippy_lints/src/serde_api.rs b/src/tools/clippy/clippy_lints/src/serde_api.rs index b36a5d6d502ea..2de22e4b6a360 100644 --- a/src/tools/clippy/clippy_lints/src/serde_api.rs +++ b/src/tools/clippy/clippy_lints/src/serde_api.rs @@ -36,9 +36,9 @@ impl<'tcx> LateLintPass<'tcx> for SerdeApi { let mut seen_str = None; let mut seen_string = None; for item in *items { - match item.ident.name { - sym::visit_str => seen_str = Some(item.span), - sym::visit_string => seen_string = Some(item.span), + match cx.tcx.item_name(item.owner_id) { + sym::visit_str => seen_str = Some(cx.tcx.def_span(item.owner_id)), + sym::visit_string => seen_string = Some(cx.tcx.def_span(item.owner_id)), _ => {}, } } diff --git a/src/tools/clippy/clippy_utils/src/paths.rs b/src/tools/clippy/clippy_utils/src/paths.rs index 8bbcb220210af..c681806517afb 100644 --- a/src/tools/clippy/clippy_utils/src/paths.rs +++ b/src/tools/clippy/clippy_utils/src/paths.rs @@ -10,7 +10,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir::def::Namespace::{MacroNS, TypeNS, ValueNS}; use rustc_hir::def::{DefKind, Namespace, Res}; use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId}; -use rustc_hir::{ImplItemRef, ItemKind, Node, OwnerId, TraitItemRef, UseKind}; +use rustc_hir::{ItemKind, Node, UseKind}; use rustc_lint::LateContext; use rustc_middle::ty::fast_reject::SimplifiedType; use rustc_middle::ty::{FloatTy, IntTy, Ty, TyCtxt, UintTy}; @@ -284,14 +284,6 @@ fn local_item_child_by_name(tcx: TyCtxt<'_>, local_id: LocalDefId, ns: PathNS, n _ => return None, }; - let res = |ident: Ident, owner_id: OwnerId| { - if ident.name == name && ns.matches(tcx.def_kind(owner_id).ns()) { - Some(owner_id.to_def_id()) - } else { - None - } - }; - match item_kind { ItemKind::Mod(_, r#mod) => r#mod.item_ids.iter().find_map(|&item_id| { let item = tcx.hir_item(item_id); @@ -307,17 +299,19 @@ fn local_item_child_by_name(tcx: TyCtxt<'_>, local_id: LocalDefId, ns: PathNS, n } else { None } + } else if let Some(ident) = item.kind.ident() + && ident.name == name + && ns.matches(tcx.def_kind(item.owner_id).ns()) + { + Some(item.owner_id.to_def_id()) } else { - res(item.kind.ident()?, item_id.owner_id) + None } }), - ItemKind::Impl(r#impl) => r#impl - .items - .iter() - .find_map(|&ImplItemRef { ident, id, .. }| res(ident, id.owner_id)), - ItemKind::Trait(.., trait_item_refs) => trait_item_refs - .iter() - .find_map(|&TraitItemRef { ident, id, .. }| res(ident, id.owner_id)), + ItemKind::Impl(..) | ItemKind::Trait(..) + => tcx.associated_items(local_id).filter_by_name_unhygienic(name) + .find(|assoc_item| ns.matches(Some(assoc_item.namespace()))) + .map(|assoc_item| assoc_item.def_id), _ => None, } } diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.default.stderr b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.default.stderr index a3c35a31c3314..87e4b0c5c7d0a 100644 --- a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.default.stderr +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.default.stderr @@ -136,13 +136,13 @@ error: incorrect ordering of trait items (defined order: [Const, Type, Fn]) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:155:5 | LL | const A: bool; - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ | note: should be placed before `SomeType` --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:153:5 | LL | type SomeType; - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ error: incorrect ordering of items (must be alphabetically ordered) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:171:11 @@ -172,13 +172,13 @@ error: incorrect ordering of impl items (defined order: [Const, Type, Fn]) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:189:5 | LL | const A: bool = false; - | ^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ | note: should be placed before `SomeType` --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:187:5 | LL | type SomeType = (); - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ error: aborting due to 15 previous errors diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.default_exp.stderr b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.default_exp.stderr index a3c35a31c3314..87e4b0c5c7d0a 100644 --- a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.default_exp.stderr +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.default_exp.stderr @@ -136,13 +136,13 @@ error: incorrect ordering of trait items (defined order: [Const, Type, Fn]) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:155:5 | LL | const A: bool; - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ | note: should be placed before `SomeType` --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:153:5 | LL | type SomeType; - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ error: incorrect ordering of items (must be alphabetically ordered) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:171:11 @@ -172,13 +172,13 @@ error: incorrect ordering of impl items (defined order: [Const, Type, Fn]) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:189:5 | LL | const A: bool = false; - | ^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ | note: should be placed before `SomeType` --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:187:5 | LL | type SomeType = (); - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ error: aborting due to 15 previous errors diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.ord_within.stderr b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.ord_within.stderr index 3fdd706fc627f..40505e2a1c452 100644 --- a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.ord_within.stderr +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.ord_within.stderr @@ -211,13 +211,13 @@ error: incorrect ordering of trait items (defined order: [Const, Type, Fn]) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:155:5 | LL | const A: bool; - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ | note: should be placed before `SomeType` --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:153:5 | LL | type SomeType; - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ error: incorrect ordering of items (must be alphabetically ordered) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:171:11 @@ -247,13 +247,13 @@ error: incorrect ordering of impl items (defined order: [Const, Type, Fn]) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:189:5 | LL | const A: bool = false; - | ^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ | note: should be placed before `SomeType` --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:187:5 | LL | type SomeType = (); - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ error: incorrect ordering of items (must be alphabetically ordered) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed.rs:207:11 diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed_var_1.var_1.stderr b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed_var_1.var_1.stderr index 730f12c38a0d3..d8db2243d4171 100644 --- a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed_var_1.var_1.stderr +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed_var_1.var_1.stderr @@ -28,25 +28,25 @@ error: incorrect ordering of impl items (defined order: [Fn, Type, Const]) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed_var_1.rs:119:5 | LL | type SomeType = (); - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ | note: should be placed before `A` --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed_var_1.rs:117:5 | LL | const A: bool = false; - | ^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ error: incorrect ordering of impl items (defined order: [Fn, Type, Const]) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed_var_1.rs:122:5 | LL | fn a() {} - | ^^^^^^^^^ + | ^^^^^^ | note: should be placed before `SomeType` --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed_var_1.rs:119:5 | LL | type SomeType = (); - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ error: incorrect ordering of items (must be alphabetically ordered) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed_var_1.rs:149:8 @@ -76,13 +76,13 @@ error: incorrect ordering of trait items (defined order: [Fn, Type, Const]) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed_var_1.rs:163:5 | LL | type SomeType; - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ | note: should be placed before `A` --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed_var_1.rs:161:5 | LL | const A: bool; - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ error: incorrect ordering of trait items (defined order: [Fn, Type, Const]) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed_var_1.rs:166:5 @@ -94,7 +94,7 @@ note: should be placed before `SomeType` --> tests/ui-toml/arbitrary_source_item_ordering/ordering_mixed_var_1.rs:163:5 | LL | type SomeType; - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ error: aborting due to 8 previous errors diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_only_impl.only_impl.stderr b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_only_impl.only_impl.stderr index 77596ba23946d..7f6bddf8005fe 100644 --- a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_only_impl.only_impl.stderr +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_only_impl.only_impl.stderr @@ -16,25 +16,25 @@ error: incorrect ordering of impl items (defined order: [Const, Type, Fn]) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_only_impl.rs:46:5 | LL | type SomeType = i8; - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ | note: should be placed before `a` --> tests/ui-toml/arbitrary_source_item_ordering/ordering_only_impl.rs:43:5 | LL | fn a() {} - | ^^^^^^^^^ + | ^^^^^^ error: incorrect ordering of impl items (defined order: [Const, Type, Fn]) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_only_impl.rs:49:5 | LL | const A: bool = true; - | ^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ | note: should be placed before `SomeType` --> tests/ui-toml/arbitrary_source_item_ordering/ordering_only_impl.rs:46:5 | LL | type SomeType = i8; - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ error: aborting due to 3 previous errors diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_only_trait.only_trait.stderr b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_only_trait.only_trait.stderr index 3d903330be8f5..a7cff238b785b 100644 --- a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_only_trait.only_trait.stderr +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_only_trait.only_trait.stderr @@ -28,13 +28,13 @@ error: incorrect ordering of trait items (defined order: [Const, Type, Fn]) --> tests/ui-toml/arbitrary_source_item_ordering/ordering_only_trait.rs:45:5 | LL | const A: bool; - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ | note: should be placed before `SomeType` --> tests/ui-toml/arbitrary_source_item_ordering/ordering_only_trait.rs:43:5 | LL | type SomeType; - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ error: aborting due to 3 previous errors diff --git a/src/tools/clippy/tests/ui/partialeq_ne_impl.stderr b/src/tools/clippy/tests/ui/partialeq_ne_impl.stderr index dc01a375060b9..0f700654f7ccc 100644 --- a/src/tools/clippy/tests/ui/partialeq_ne_impl.stderr +++ b/src/tools/clippy/tests/ui/partialeq_ne_impl.stderr @@ -1,12 +1,8 @@ error: re-implementing `PartialEq::ne` is unnecessary --> tests/ui/partialeq_ne_impl.rs:9:5 | -LL | / fn ne(&self, _: &Foo) -> bool { -LL | | -LL | | -LL | | false -LL | | } - | |_____^ +LL | fn ne(&self, _: &Foo) -> bool { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `-D clippy::partialeq-ne-impl` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::partialeq_ne_impl)]` diff --git a/src/tools/clippy/tests/ui/same_name_method.stderr b/src/tools/clippy/tests/ui/same_name_method.stderr index b2624ac4d2644..bf7456d80e2a3 100644 --- a/src/tools/clippy/tests/ui/same_name_method.stderr +++ b/src/tools/clippy/tests/ui/same_name_method.stderr @@ -2,13 +2,13 @@ error: method's name is the same as an existing method in a trait --> tests/ui/same_name_method.rs:20:13 | LL | fn foo() {} - | ^^^^^^^^^^^ + | ^^^^^^^^ | note: existing `foo` defined here --> tests/ui/same_name_method.rs:25:13 | LL | fn foo() {} - | ^^^^^^^^^^^ + | ^^^^^^^^ = note: `-D clippy::same-name-method` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::same_name_method)]` @@ -16,7 +16,7 @@ error: method's name is the same as an existing method in a trait --> tests/ui/same_name_method.rs:35:13 | LL | fn clone() {} - | ^^^^^^^^^^^^^ + | ^^^^^^^^^^ | note: existing `clone` defined here --> tests/ui/same_name_method.rs:31:18 @@ -28,19 +28,19 @@ error: method's name is the same as an existing method in a trait --> tests/ui/same_name_method.rs:46:13 | LL | fn foo() {} - | ^^^^^^^^^^^ + | ^^^^^^^^ | note: existing `foo` defined here --> tests/ui/same_name_method.rs:51:13 | LL | fn foo() {} - | ^^^^^^^^^^^ + | ^^^^^^^^ error: method's name is the same as an existing method in a trait --> tests/ui/same_name_method.rs:61:13 | LL | fn foo() {} - | ^^^^^^^^^^^ + | ^^^^^^^^ | note: existing `foo` defined here --> tests/ui/same_name_method.rs:65:9 @@ -52,7 +52,7 @@ error: method's name is the same as an existing method in a trait --> tests/ui/same_name_method.rs:74:13 | LL | fn foo() {} - | ^^^^^^^^^^^ + | ^^^^^^^^ | note: existing `foo` defined here --> tests/ui/same_name_method.rs:79:9 @@ -64,7 +64,7 @@ error: method's name is the same as an existing method in a trait --> tests/ui/same_name_method.rs:74:13 | LL | fn foo() {} - | ^^^^^^^^^^^ + | ^^^^^^^^ | note: existing `foo` defined here --> tests/ui/same_name_method.rs:81:9 diff --git a/src/tools/clippy/tests/ui/serde.stderr b/src/tools/clippy/tests/ui/serde.stderr index eb6b7c6b0c36a..652248e3578c7 100644 --- a/src/tools/clippy/tests/ui/serde.stderr +++ b/src/tools/clippy/tests/ui/serde.stderr @@ -5,10 +5,7 @@ LL | / fn visit_string(self, _v: String) -> Result LL | | LL | | where LL | | E: serde::de::Error, -LL | | { -LL | | unimplemented!() -LL | | } - | |_____^ + | |____________________________^ | = note: `-D clippy::serde-api-misuse` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::serde_api_misuse)]` diff --git a/tests/codegen/sanitizer/cfi/emit-type-metadata-id-itanium-cxx-abi-paths.rs b/tests/codegen/sanitizer/cfi/emit-type-metadata-id-itanium-cxx-abi-paths.rs index a8ba8db1be3b4..e1527bf1edc2d 100644 --- a/tests/codegen/sanitizer/cfi/emit-type-metadata-id-itanium-cxx-abi-paths.rs +++ b/tests/codegen/sanitizer/cfi/emit-type-metadata-id-itanium-cxx-abi-paths.rs @@ -78,9 +78,9 @@ pub fn foo12(_: &Type4, _: &Type4, _: &Type4) {} // CHECK: ![[TYPE4]] = !{i64 0, !"_ZTSFvu3refIu{{[0-9]+}}NtNCNvC{{[[:print:]]+}}_{{[[:print:]]+}}3foo11{{[{}][{}]}}closure{{[}][}]}}3FooEE"} // CHECK: ![[TYPE5]] = !{i64 0, !"_ZTSFvu3refIu{{[0-9]+}}NtNCNvC{{[[:print:]]+}}_{{[[:print:]]+}}3foo11{{[{}][{}]}}closure{{[}][}]}}3FooES0_E"} // CHECK: ![[TYPE6]] = !{i64 0, !"_ZTSFvu3refIu{{[0-9]+}}NtNCNvC{{[[:print:]]+}}_{{[[:print:]]+}}3foo11{{[{}][{}]}}closure{{[}][}]}}3FooES0_S0_E"} -// CHECK: ![[TYPE7]] = !{i64 0, !"_ZTSFvu3refIu{{[0-9]+}}NtNkNvC{{[[:print:]]+}}_{{[[:print:]]+}}3foo12{{[{}][{}]}}constant{{[}][}]}}3FooEE"} -// CHECK: ![[TYPE8]] = !{i64 0, !"_ZTSFvu3refIu{{[0-9]+}}NtNkNvC{{[[:print:]]+}}_{{[[:print:]]+}}3foo12{{[{}][{}]}}constant{{[}][}]}}3FooES0_E"} -// CHECK: ![[TYPE9]] = !{i64 0, !"_ZTSFvu3refIu{{[0-9]+}}NtNkNvC{{[[:print:]]+}}_{{[[:print:]]+}}3foo12{{[{}][{}]}}constant{{[}][}]}}3FooES0_S0_E"} +// CHECK: ![[TYPE7]] = !{i64 0, !"_ZTSFvu3refIu{{[0-9]+}}NtNKNvC{{[[:print:]]+}}_{{[[:print:]]+}}3foo12{{[{}][{}]}}constant{{[}][}]}}3FooEE"} +// CHECK: ![[TYPE8]] = !{i64 0, !"_ZTSFvu3refIu{{[0-9]+}}NtNKNvC{{[[:print:]]+}}_{{[[:print:]]+}}3foo12{{[{}][{}]}}constant{{[}][}]}}3FooES0_E"} +// CHECK: ![[TYPE9]] = !{i64 0, !"_ZTSFvu3refIu{{[0-9]+}}NtNKNvC{{[[:print:]]+}}_{{[[:print:]]+}}3foo12{{[{}][{}]}}constant{{[}][}]}}3FooES0_S0_E"} // CHECK: ![[TYPE10]] = !{i64 0, !"_ZTSFvu3refIu{{[0-9]+}}NvNINvC{{[[:print:]]+}}_{{[[:print:]]+}}3foo8{{[{}][{}]}}impl{{[}][}]}}3barEE"} // CHECK: ![[TYPE11]] = !{i64 0, !"_ZTSFvu3refIu{{[0-9]+}}NvNINvC{{[[:print:]]+}}_{{[[:print:]]+}}3foo8{{[{}][{}]}}impl{{[}][}]}}3barES0_E"} // CHECK: ![[TYPE12]] = !{i64 0, !"_ZTSFvu3refIu{{[0-9]+}}NvNINvC{{[[:print:]]+}}_{{[[:print:]]+}}3foo8{{[{}][{}]}}impl{{[}][}]}}3barES0_S0_E"} diff --git a/tests/incremental/hashes/inherent_impls.rs b/tests/incremental/hashes/inherent_impls.rs index caea394977a73..044c3d2b86c13 100644 --- a/tests/incremental/hashes/inherent_impls.rs +++ b/tests/incremental/hashes/inherent_impls.rs @@ -150,7 +150,7 @@ impl Foo { } #[cfg(not(any(cfail1,cfail4)))] -#[rustc_clean(cfg="cfail2", except="opt_hir_owner_nodes")] +#[rustc_clean(cfg="cfail2")] #[rustc_clean(cfg="cfail3")] #[rustc_clean(cfg="cfail5", except="opt_hir_owner_nodes")] #[rustc_clean(cfg="cfail6")] diff --git a/tests/incremental/hashes/trait_impls.rs b/tests/incremental/hashes/trait_impls.rs index 8faf6806b90b4..a89b5b3e78298 100644 --- a/tests/incremental/hashes/trait_impls.rs +++ b/tests/incremental/hashes/trait_impls.rs @@ -141,7 +141,7 @@ pub trait ChangeMethodSelfnessTrait { } #[cfg(not(any(cfail1,cfail4)))] -#[rustc_clean(except="opt_hir_owner_nodes", cfg="cfail2")] +#[rustc_clean(cfg="cfail2")] #[rustc_clean(cfg="cfail3")] #[rustc_clean(except="opt_hir_owner_nodes", cfg="cfail5")] #[rustc_clean(cfg="cfail6")] @@ -179,7 +179,7 @@ pub trait RemoveMethodSelfnessTrait { } #[cfg(not(any(cfail1,cfail4)))] -#[rustc_clean(except="opt_hir_owner_nodes", cfg="cfail2")] +#[rustc_clean(cfg="cfail2")] #[rustc_clean(cfg="cfail3")] #[rustc_clean(except="opt_hir_owner_nodes", cfg="cfail5")] #[rustc_clean(cfg="cfail6")] diff --git a/tests/ui/associated-consts/issue-58022.stderr b/tests/ui/associated-consts/issue-58022.stderr index 37cb162b2b221..5d57e01d6f59c 100644 --- a/tests/ui/associated-consts/issue-58022.stderr +++ b/tests/ui/associated-consts/issue-58022.stderr @@ -16,7 +16,7 @@ error[E0790]: cannot refer to the associated constant on trait without specifyin --> $DIR/issue-58022.rs:4:25 | LL | const SIZE: usize; - | ------------------ `Foo::SIZE` defined here + | ----------------- `Foo::SIZE` defined here LL | LL | fn new(slice: &[u8; Foo::SIZE]) -> Self; | ^^^^^^^^^ cannot refer to the associated constant of trait diff --git a/tests/ui/associated-consts/issue-63496.stderr b/tests/ui/associated-consts/issue-63496.stderr index f2a4e01adea43..bdd2769afc86a 100644 --- a/tests/ui/associated-consts/issue-63496.stderr +++ b/tests/ui/associated-consts/issue-63496.stderr @@ -2,7 +2,7 @@ error[E0790]: cannot refer to the associated constant on trait without specifyin --> $DIR/issue-63496.rs:4:21 | LL | const C: usize; - | --------------- `A::C` defined here + | -------------- `A::C` defined here LL | LL | fn f() -> ([u8; A::C], [u8; A::C]); | ^^^^ cannot refer to the associated constant of trait @@ -11,7 +11,7 @@ error[E0790]: cannot refer to the associated constant on trait without specifyin --> $DIR/issue-63496.rs:4:33 | LL | const C: usize; - | --------------- `A::C` defined here + | -------------- `A::C` defined here LL | LL | fn f() -> ([u8; A::C], [u8; A::C]); | ^^^^ cannot refer to the associated constant of trait diff --git a/tests/ui/associated-item/issue-48027.stderr b/tests/ui/associated-item/issue-48027.stderr index 513961e2bd0ad..e5c1ced934136 100644 --- a/tests/ui/associated-item/issue-48027.stderr +++ b/tests/ui/associated-item/issue-48027.stderr @@ -18,7 +18,7 @@ error[E0790]: cannot refer to the associated constant on trait without specifyin --> $DIR/issue-48027.rs:3:32 | LL | const X: usize; - | --------------- `Bar::X` defined here + | -------------- `Bar::X` defined here LL | fn return_n(&self) -> [u8; Bar::X]; | ^^^^^^ cannot refer to the associated constant of trait diff --git a/tests/ui/associated-types/defaults-in-other-trait-items.stderr b/tests/ui/associated-types/defaults-in-other-trait-items.stderr index bdcfadd3955d2..56abd6ebf73b2 100644 --- a/tests/ui/associated-types/defaults-in-other-trait-items.stderr +++ b/tests/ui/associated-types/defaults-in-other-trait-items.stderr @@ -2,7 +2,7 @@ error[E0308]: mismatched types --> $DIR/defaults-in-other-trait-items.rs:9:13 | LL | type A = (); - | ------------ associated type defaults can't be assumed inside the trait defining them + | ------ associated type defaults can't be assumed inside the trait defining them ... LL | let () = p; | ^^ - this expression has type `::A` @@ -16,7 +16,7 @@ error[E0308]: mismatched types --> $DIR/defaults-in-other-trait-items.rs:36:25 | LL | type Ty = u8; - | ------------- associated type defaults can't be assumed inside the trait defining them + | ------- associated type defaults can't be assumed inside the trait defining them ... LL | const C: Self::Ty = 0u8; | ^^^ expected associated type, found `u8` @@ -28,7 +28,7 @@ error[E0308]: mismatched types --> $DIR/defaults-in-other-trait-items.rs:54:9 | LL | type Res = isize; - | ----------------- associated type defaults can't be assumed inside the trait defining them + | -------- associated type defaults can't be assumed inside the trait defining them LL | LL | fn infer_me_correctly() -> Self::Res { | --------- expected `::Res` because of return type diff --git a/tests/ui/associated-types/defaults-specialization.stderr b/tests/ui/associated-types/defaults-specialization.stderr index fd2a1a0c2d13a..7d19ac85982a3 100644 --- a/tests/ui/associated-types/defaults-specialization.stderr +++ b/tests/ui/associated-types/defaults-specialization.stderr @@ -31,7 +31,7 @@ error[E0053]: method `make` has an incompatible type for trait --> $DIR/defaults-specialization.rs:35:18 | LL | default type Ty = bool; - | ----------------------- associated type is `default` and may be overridden + | --------------- associated type is `default` and may be overridden LL | LL | fn make() -> bool { true } | ^^^^ expected associated type, found `bool` @@ -53,7 +53,7 @@ error[E0308]: mismatched types --> $DIR/defaults-specialization.rs:10:9 | LL | type Ty = u8; - | ------------- associated type defaults can't be assumed inside the trait defining them + | ------- associated type defaults can't be assumed inside the trait defining them LL | LL | fn make() -> Self::Ty { | -------- expected `::Ty` because of return type @@ -80,7 +80,7 @@ error[E0308]: mismatched types --> $DIR/defaults-specialization.rs:44:29 | LL | default type Ty = bool; - | ----------------------- associated type is `default` and may be overridden + | --------------- associated type is `default` and may be overridden LL | LL | fn make() -> Self::Ty { true } | -------- ^^^^ expected associated type, found `bool` diff --git a/tests/ui/associated-types/issue-26681.stderr b/tests/ui/associated-types/issue-26681.stderr index b64bcee07f043..5fb1a4ef3f5f0 100644 --- a/tests/ui/associated-types/issue-26681.stderr +++ b/tests/ui/associated-types/issue-26681.stderr @@ -2,7 +2,7 @@ error[E0308]: mismatched types --> $DIR/issue-26681.rs:17:39 | LL | type Fv: Foo = u8; - | ------------------ associated type defaults can't be assumed inside the trait defining them + | ------------ associated type defaults can't be assumed inside the trait defining them LL | const C: ::Bar = 6665; | ^^^^ expected associated type, found integer | diff --git a/tests/ui/consts/issue-54954.stderr b/tests/ui/consts/issue-54954.stderr index b8c983eb7b81c..2ef3abcf7603b 100644 --- a/tests/ui/consts/issue-54954.stderr +++ b/tests/ui/consts/issue-54954.stderr @@ -10,14 +10,11 @@ LL | const fn const_val() -> usize { error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type --> $DIR/issue-54954.rs:1:24 | -LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot call associated function of trait +LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot call associated function of trait ... -LL | / const fn const_val() -> usize { -LL | | -LL | | core::mem::size_of::() -LL | | } - | |_____- `Tt::const_val` defined here +LL | const fn const_val() -> usize { + | --------------------------------------- `Tt::const_val` defined here error: aborting due to 2 previous errors diff --git a/tests/ui/error-codes/E0790.stderr b/tests/ui/error-codes/E0790.stderr index 106554b24253e..93c43020768c7 100644 --- a/tests/ui/error-codes/E0790.stderr +++ b/tests/ui/error-codes/E0790.stderr @@ -16,7 +16,7 @@ error[E0790]: cannot refer to the associated constant on trait without specifyin --> $DIR/E0790.rs:21:17 | LL | const MY_ASSOC_CONST: (); - | ------------------------- `MyTrait::MY_ASSOC_CONST` defined here + | ------------------------ `MyTrait::MY_ASSOC_CONST` defined here ... LL | let _ = MyTrait::MY_ASSOC_CONST; | ^^^^^^^^^^^^^^^^^^^^^^^ cannot refer to the associated constant of trait @@ -44,7 +44,7 @@ error[E0790]: cannot refer to the associated constant on trait without specifyin --> $DIR/E0790.rs:30:13 | LL | const MY_ASSOC_CONST: (); - | ------------------------- `MyTrait::MY_ASSOC_CONST` defined here + | ------------------------ `MyTrait::MY_ASSOC_CONST` defined here ... LL | let _ = inner::MyTrait::MY_ASSOC_CONST; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot refer to the associated constant of trait diff --git a/tests/ui/feature-gates/feature-gate-async-drop.stderr b/tests/ui/feature-gates/feature-gate-async-drop.stderr index e795c3a342269..80f6228a16fe3 100644 --- a/tests/ui/feature-gates/feature-gate-async-drop.stderr +++ b/tests/ui/feature-gates/feature-gate-async-drop.stderr @@ -12,7 +12,7 @@ error[E0658]: use of unstable library feature `async_drop` --> $DIR/feature-gate-async-drop.rs:13:5 | LL | async fn drop(self: Pin<&mut Self>) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: see issue #126482 for more information = help: add `#![feature(async_drop)]` to the crate attributes to enable diff --git a/tests/ui/generics/export-name-on-generics.stderr b/tests/ui/generics/export-name-on-generics.stderr index 7bc7b8ca55931..e08b2b1c8f319 100644 --- a/tests/ui/generics/export-name-on-generics.stderr +++ b/tests/ui/generics/export-name-on-generics.stderr @@ -4,7 +4,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "foo"] | ---------------------- help: remove this attribute LL | pub fn foo() {} - | ^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | note: the lint level is defined here --> $DIR/export-name-on-generics.rs:3:9 @@ -18,7 +18,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "bar"] | ---------------------- help: remove this attribute LL | pub extern "C" fn bar() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:21:5 @@ -26,7 +26,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "foo"] | ---------------------- help: remove this attribute LL | pub fn foo() {} - | ^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:24:5 @@ -34,7 +34,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "bar"] | ---------------------- help: remove this attribute LL | pub extern "C" fn bar() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:42:5 @@ -42,7 +42,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "foo"] | ---------------------- help: remove this attribute LL | fn foo() {} - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:45:5 @@ -50,7 +50,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "bar"] | ---------------------- help: remove this attribute LL | extern "C" fn bar() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:64:5 @@ -58,7 +58,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "foo"] | ---------------------- help: remove this attribute LL | fn foo() {} - | ^^^^^^^^^^^ + | ^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:67:5 @@ -66,7 +66,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "foo2"] | ----------------------- help: remove this attribute LL | fn foo2() {} - | ^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:70:5 @@ -74,7 +74,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "baz"] | ---------------------- help: remove this attribute LL | extern "C" fn bar() {} - | ^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:73:5 @@ -82,7 +82,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "baz"] | ---------------------- help: remove this attribute LL | fn baz(x: &i32) -> &i32 { x } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:76:5 @@ -90,7 +90,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "qux"] | ---------------------- help: remove this attribute LL | fn qux<'a>(x: &'a i32) -> &i32 { x } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:83:5 @@ -98,7 +98,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "foo"] | ---------------------- help: remove this attribute LL | pub fn foo() {} - | ^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:86:5 @@ -106,7 +106,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "bar"] | ---------------------- help: remove this attribute LL | pub extern "C" fn bar() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:89:5 @@ -114,7 +114,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "baz"] | ---------------------- help: remove this attribute LL | pub fn baz() {} - | ^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:105:5 @@ -122,7 +122,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "foo"] | ---------------------- help: remove this attribute LL | fn foo() {} - | ^^^^^^^^^^^ + | ^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:108:5 @@ -130,7 +130,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "bar"] | ---------------------- help: remove this attribute LL | extern "C" fn bar() {} - | ^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/export-name-on-generics.rs:111:5 @@ -138,7 +138,7 @@ error: functions generic over types or consts must be mangled LL | #[export_name = "baz"] | ---------------------- help: remove this attribute LL | fn baz() {} - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ error: aborting due to 17 previous errors diff --git a/tests/ui/generics/generic-no-mangle.stderr b/tests/ui/generics/generic-no-mangle.stderr index adfddbe9ca791..39fbe4dd76da1 100644 --- a/tests/ui/generics/generic-no-mangle.stderr +++ b/tests/ui/generics/generic-no-mangle.stderr @@ -4,7 +4,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | pub fn foo() {} - | ^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | note: the lint level is defined here --> $DIR/generic-no-mangle.rs:3:9 @@ -18,7 +18,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | pub extern "C" fn bar() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:21:5 @@ -26,7 +26,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | pub fn foo() {} - | ^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:24:5 @@ -34,7 +34,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | pub extern "C" fn bar() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:42:5 @@ -42,7 +42,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | fn foo() {} - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:45:5 @@ -50,7 +50,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | extern "C" fn bar() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:64:5 @@ -58,7 +58,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | fn foo() {} - | ^^^^^^^^^^^ + | ^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:67:5 @@ -66,7 +66,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | fn foo2() {} - | ^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:70:5 @@ -74,7 +74,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | extern "C" fn bar() {} - | ^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:73:5 @@ -82,7 +82,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | fn baz(x: &i32) -> &i32 { x } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:76:5 @@ -90,7 +90,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | fn qux<'a>(x: &'a i32) -> &i32 { x } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:83:5 @@ -98,7 +98,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | pub fn foo() {} - | ^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:86:5 @@ -106,7 +106,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | pub extern "C" fn bar() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:89:5 @@ -114,7 +114,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | pub fn baz() {} - | ^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:105:5 @@ -122,7 +122,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | fn foo() {} - | ^^^^^^^^^^^ + | ^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:108:5 @@ -130,7 +130,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | extern "C" fn bar() {} - | ^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^ error: functions generic over types or consts must be mangled --> $DIR/generic-no-mangle.rs:111:5 @@ -138,7 +138,7 @@ error: functions generic over types or consts must be mangled LL | #[no_mangle] | ------------ help: remove this attribute LL | fn baz() {} - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ error: aborting due to 17 previous errors diff --git a/tests/ui/invalid/invalid-rustc_legacy_const_generics-issue-123077.stderr b/tests/ui/invalid/invalid-rustc_legacy_const_generics-issue-123077.stderr index 6f5d719006d8f..111d6d524e5fb 100644 --- a/tests/ui/invalid/invalid-rustc_legacy_const_generics-issue-123077.stderr +++ b/tests/ui/invalid/invalid-rustc_legacy_const_generics-issue-123077.stderr @@ -67,9 +67,10 @@ LL | struct F(); help: try using a const generic argument instead | LL ~ std::arch::x86_64::_mm_blend_ps::<{ { -LL + struct F(); -LL + 1 -LL ~ } }>(loop {}, loop {}); +LL + struct F(); +LL + +LL + 1 +LL ~ } }>(loop {}, loop {}); | error: invalid argument to a legacy const generic: cannot have const blocks, closures, async blocks or items diff --git a/tests/ui/lint/lint-stability.stderr b/tests/ui/lint/lint-stability.stderr index a22fce70a4ad5..fd57908a77b53 100644 --- a/tests/ui/lint/lint-stability.stderr +++ b/tests/ui/lint/lint-stability.stderr @@ -290,7 +290,7 @@ error[E0658]: use of unstable library feature `unstable_test_feature` --> $DIR/lint-stability.rs:179:9 | LL | fn trait_unstable(&self) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^ | = help: add `#![feature(unstable_test_feature)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date diff --git a/tests/ui/lint/suggestions.stderr b/tests/ui/lint/suggestions.stderr index a4871ead74b8b..c35e92f59809a 100644 --- a/tests/ui/lint/suggestions.stderr +++ b/tests/ui/lint/suggestions.stderr @@ -65,7 +65,7 @@ LL | #[no_mangle] | ------------ help: remove this attribute LL | LL | pub fn defiant(_t: T) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(no_mangle_generic_items)]` on by default @@ -89,7 +89,7 @@ warning: functions generic over types or consts must be mangled --> $DIR/suggestions.rs:26:18 | LL | #[no_mangle] pub fn val_jean() {} - | ------------ ^^^^^^^^^^^^^^^^^^^^^^^ + | ------------ ^^^^^^^^^^^^^^^^^^^^ | | | help: remove this attribute @@ -105,7 +105,7 @@ warning: functions generic over types or consts must be mangled --> $DIR/suggestions.rs:35:18 | LL | #[no_mangle] pub(crate) fn crossfield() {} - | ------------ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ------------ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | help: remove this attribute diff --git a/tests/ui/specialization/specialization-default-types.current.stderr b/tests/ui/specialization/specialization-default-types.current.stderr index 67477f9a6d537..09689681740ff 100644 --- a/tests/ui/specialization/specialization-default-types.current.stderr +++ b/tests/ui/specialization/specialization-default-types.current.stderr @@ -12,7 +12,7 @@ error[E0308]: mismatched types --> $DIR/specialization-default-types.rs:19:9 | LL | default type Output = Box; - | ----------------------------- associated type is `default` and may be overridden + | ------------------- associated type is `default` and may be overridden LL | default fn generate(self) -> Self::Output { | ------------ expected `::Output` because of return type LL | Box::new(self) diff --git a/tests/ui/specialization/specialization-default-types.next.stderr b/tests/ui/specialization/specialization-default-types.next.stderr index 4f7c47654460e..1535c6473bddf 100644 --- a/tests/ui/specialization/specialization-default-types.next.stderr +++ b/tests/ui/specialization/specialization-default-types.next.stderr @@ -12,7 +12,7 @@ error[E0308]: mismatched types --> $DIR/specialization-default-types.rs:19:9 | LL | default type Output = Box; - | ----------------------------- associated type is `default` and may be overridden + | ------------------- associated type is `default` and may be overridden LL | default fn generate(self) -> Self::Output { | ------------ expected `::Output` because of return type LL | Box::new(self) diff --git a/tests/ui/stats/input-stats.stderr b/tests/ui/stats/input-stats.stderr index eb038bbcaf1a2..72a9820bb6431 100644 --- a/tests/ui/stats/input-stats.stderr +++ b/tests/ui/stats/input-stats.stderr @@ -107,17 +107,17 @@ hir-stats WherePredicate 72 (NN.N%) 3 24 hir-stats - BoundPredicate 72 (NN.N%) 3 hir-stats Local 72 (NN.N%) 1 72 hir-stats InlineAsm 72 (NN.N%) 1 72 -hir-stats ImplItemRef 72 (NN.N%) 2 36 hir-stats Body 72 (NN.N%) 3 24 hir-stats Param 64 (NN.N%) 2 32 hir-stats GenericArg 64 (NN.N%) 4 16 hir-stats - Type 16 (NN.N%) 1 hir-stats - Lifetime 48 (NN.N%) 3 -hir-stats TraitItemRef 56 (NN.N%) 2 28 hir-stats ExprField 40 (NN.N%) 1 40 hir-stats Mod 32 (NN.N%) 1 32 hir-stats Lifetime 28 (NN.N%) 1 28 -hir-stats ForeignItemRef 24 (NN.N%) 1 24 +hir-stats TraitItemId 8 (NN.N%) 2 4 +hir-stats ImplItemId 8 (NN.N%) 2 4 +hir-stats ForeignItemId 4 (NN.N%) 1 4 hir-stats ---------------------------------------------------------------- -hir-stats Total 8_716 173 +hir-stats Total 8_584 173 hir-stats ================================================================ diff --git a/tests/ui/suggestions/issue-104327.stderr b/tests/ui/suggestions/issue-104327.stderr index 1bad82d471e04..4515fe223c7d9 100644 --- a/tests/ui/suggestions/issue-104327.stderr +++ b/tests/ui/suggestions/issue-104327.stderr @@ -2,7 +2,7 @@ error[E0790]: cannot call associated function on trait without specifying the co --> $DIR/issue-104327.rs:10:5 | LL | fn f() {} - | --------- `Foo::f` defined here + | ------ `Foo::f` defined here ... LL | Foo::f(); | ^^^^^^^^ cannot call associated function of trait diff --git a/tests/ui/traits/default-method/rustc_must_implement_one_of_misuse.stderr b/tests/ui/traits/default-method/rustc_must_implement_one_of_misuse.stderr index 38e692521ca23..cf197d035b38f 100644 --- a/tests/ui/traits/default-method/rustc_must_implement_one_of_misuse.stderr +++ b/tests/ui/traits/default-method/rustc_must_implement_one_of_misuse.stderr @@ -50,7 +50,7 @@ error: not a function --> $DIR/rustc_must_implement_one_of_misuse.rs:26:5 | LL | const A: u8 = 1; - | ^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | note: required by this annotation --> $DIR/rustc_must_implement_one_of_misuse.rs:24:1 @@ -63,7 +63,7 @@ error: not a function --> $DIR/rustc_must_implement_one_of_misuse.rs:28:5 | LL | type B; - | ^^^^^^^ + | ^^^^^^ | note: required by this annotation --> $DIR/rustc_must_implement_one_of_misuse.rs:24:1 diff --git a/tests/ui/traits/trait-upcasting/deref-upcast-shadowing-lint.stderr b/tests/ui/traits/trait-upcasting/deref-upcast-shadowing-lint.stderr index 0d7f957a50ebd..6744899e9518f 100644 --- a/tests/ui/traits/trait-upcasting/deref-upcast-shadowing-lint.stderr +++ b/tests/ui/traits/trait-upcasting/deref-upcast-shadowing-lint.stderr @@ -5,7 +5,7 @@ LL | impl<'a> Deref for dyn Foo + 'a { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `dyn Foo` implements `Deref>` which conflicts with supertrait `Bar` LL | LL | type Target = dyn Bar + 'a; - | -------------------------------- target type is a supertrait of `dyn Foo` + | ----------- target type is a supertrait of `dyn Foo` | note: the lint level is defined here --> $DIR/deref-upcast-shadowing-lint.rs:2:9 diff --git a/tests/ui/traits/trait-upcasting/migrate-lint-deny-regions.stderr b/tests/ui/traits/trait-upcasting/migrate-lint-deny-regions.stderr index 806c57e44a2bf..0d43563e1ab78 100644 --- a/tests/ui/traits/trait-upcasting/migrate-lint-deny-regions.stderr +++ b/tests/ui/traits/trait-upcasting/migrate-lint-deny-regions.stderr @@ -5,7 +5,7 @@ LL | impl<'a> Deref for dyn Foo<'a> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `dyn Foo<'_>` implements `Deref>` which conflicts with supertrait `Bar<'_>` LL | LL | type Target = dyn Bar<'a>; - | -------------------------- target type is a supertrait of `dyn Foo<'_>` + | ----------- target type is a supertrait of `dyn Foo<'_>` | note: the lint level is defined here --> $DIR/migrate-lint-deny-regions.rs:2:9 diff --git a/tests/ui/traits/trait-upcasting/migrate-lint-different-substs.stderr b/tests/ui/traits/trait-upcasting/migrate-lint-different-substs.stderr index 86cff5233ff49..a483e98efea1a 100644 --- a/tests/ui/traits/trait-upcasting/migrate-lint-different-substs.stderr +++ b/tests/ui/traits/trait-upcasting/migrate-lint-different-substs.stderr @@ -5,7 +5,7 @@ LL | impl<'a> Deref for dyn Foo + 'a { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `dyn Foo` implements `Deref>` which conflicts with supertrait `Bar` LL | LL | type Target = dyn Bar + 'a; - | -------------------------------- target type is a supertrait of `dyn Foo` + | ----------- target type is a supertrait of `dyn Foo` | note: the lint level is defined here --> $DIR/migrate-lint-different-substs.rs:2:9