diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 9b1642df11401..c50bca967cc20 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -11,7 +11,7 @@ use rustc_hir as hir; use rustc_hir::def::Res; use rustc_session::parse::feature_err; use rustc_span::hygiene::ForLoopLoc; -use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned}; +use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned, DUMMY_SP}; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_target::asm; use std::collections::hash_map::Entry; @@ -229,6 +229,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // Include parens in span, but only if it is a super-span. if e.span.contains(ex.span) { ex.span = e.span; + self.spans[ex.hir_id] = e.span; } // Merge attributes into the inner expression. let mut attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect(); @@ -246,7 +247,7 @@ impl<'hir> LoweringContext<'_, 'hir> { }; hir::Expr { - hir_id: self.lower_node_id(e.id), + hir_id: self.lower_node_id(e.id, e.span), kind, span: e.span, attrs: e.attrs.iter().map(|a| self.lower_attr(a)).collect::>().into(), @@ -514,12 +515,11 @@ impl<'hir> LoweringContext<'_, 'hir> { } }); hir::Arm { - hir_id: self.next_id(), + hir_id: self.next_id(arm.span), attrs: self.lower_attrs(&arm.attrs), pat, guard, body: self.lower_expr(&arm.body), - span: arm.span, } } @@ -548,7 +548,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // Resume argument type. We let the compiler infer this to simplify the lowering. It is // fully constrained by `future::from_generator`. - let input_ty = hir::Ty { hir_id: self.next_id(), kind: hir::TyKind::Infer, span }; + let input_ty = hir::Ty { hir_id: self.next_id(span), kind: hir::TyKind::Infer, span }; // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`. let decl = self.arena.alloc(hir::FnDecl { @@ -564,7 +564,7 @@ impl<'hir> LoweringContext<'_, 'hir> { Ident::with_dummy_span(sym::_task_context), hir::BindingAnnotation::Mutable, ); - let param = hir::Param { attrs: &[], hir_id: self.next_id(), pat, ty_span: span, span }; + let param = hir::Param { attrs: &[], hir_id: self.next_id(span), pat, ty_span: span }; let params = arena_vec![self; param]; let body_id = self.lower_body(move |this| { @@ -586,7 +586,7 @@ impl<'hir> LoweringContext<'_, 'hir> { Some(hir::Movability::Static), ); let generator = hir::Expr { - hir_id: self.lower_node_id(closure_node_id), + hir_id: self.lower_node_id(closure_node_id, span), kind: generator_kind, span, attrs: ThinVec::new(), @@ -683,7 +683,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // `::std::task::Poll::Ready(result) => break result` let loop_node_id = self.resolver.next_node_id(); - let loop_hir_id = self.lower_node_id(loop_node_id); + let loop_hir_id = self.lower_node_id(loop_node_id, span); let ready_arm = { let x_ident = Ident::with_dummy_span(sym::result); let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident); @@ -1008,11 +1008,10 @@ impl<'hir> LoweringContext<'_, 'hir> { let field_pats = self.arena.alloc_from_iter(fields.iter().map(|f| { let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments); hir::FieldPat { - hir_id: self.next_id(), + hir_id: self.next_id(f.span), ident: f.ident, pat, is_shorthand: f.is_shorthand, - span: f.span, } })); let qpath = self.lower_qpath( @@ -1149,7 +1148,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let target_id = match destination { Some((id, _)) => { if let Some(loop_id) = self.resolver.get_label_res(id) { - Ok(self.lower_node_id(loop_id)) + Ok(self.lower_node_id(loop_id, DUMMY_SP)) } else { Err(hir::LoopIdError::UnresolvedLabel) } @@ -1158,7 +1157,7 @@ impl<'hir> LoweringContext<'_, 'hir> { .loop_scopes .last() .cloned() - .map(|id| Ok(self.lower_node_id(id))) + .map(|id| Ok(self.lower_node_id(id, DUMMY_SP))) .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)), }; hir::Destination { label: destination.map(|(_, label)| label), target_id } @@ -1554,10 +1553,9 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_field(&mut self, f: &Field) -> hir::Field<'hir> { hir::Field { - hir_id: self.next_id(), + hir_id: self.next_id(f.span), ident: f.ident, expr: self.lower_expr(&f.expr), - span: f.span, is_shorthand: f.is_shorthand, } } @@ -1619,6 +1617,7 @@ impl<'hir> LoweringContext<'_, 'hir> { None, ); head.span = desugared_span; + self.spans[head.hir_id] = desugared_span; let iter = Ident::with_dummy_span(sym::iter); @@ -1705,7 +1704,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // `[opt_ident]: loop { ... }` let kind = hir::ExprKind::Loop(loop_block, opt_label, hir::LoopSource::ForLoop); let loop_expr = self.arena.alloc(hir::Expr { - hir_id: self.lower_node_id(e.id), + hir_id: self.lower_node_id(e.id, e.span), kind, span: e.span, attrs: ThinVec::new(), @@ -1832,7 +1831,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let thin_attrs = ThinVec::from(attrs); let catch_scope = self.catch_scopes.last().copied(); let ret_expr = if let Some(catch_node) = catch_scope { - let target_id = Ok(self.lower_node_id(catch_node)); + let target_id = Ok(self.lower_node_id(catch_node, DUMMY_SP)); self.arena.alloc(self.expr( try_span, hir::ExprKind::Break( @@ -2005,8 +2004,8 @@ impl<'hir> LoweringContext<'_, 'hir> { } fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> { - let hir_id = self.next_id(); let span = expr.span; + let hir_id = self.next_id(span); self.expr( span, hir::ExprKind::Block( @@ -2015,7 +2014,6 @@ impl<'hir> LoweringContext<'_, 'hir> { expr: Some(expr), hir_id, rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated), - span, targeted_by_break: false, }), None, @@ -2035,7 +2033,8 @@ impl<'hir> LoweringContext<'_, 'hir> { b: &'hir hir::Block<'hir>, attrs: AttrVec, ) -> hir::Expr<'hir> { - self.expr(b.span, hir::ExprKind::Block(b, None), attrs) + let span = self.spans[b.hir_id]; + self.expr(span, hir::ExprKind::Block(b, None), attrs) } pub(super) fn expr( @@ -2044,21 +2043,14 @@ impl<'hir> LoweringContext<'_, 'hir> { kind: hir::ExprKind<'hir>, attrs: AttrVec, ) -> hir::Expr<'hir> { - hir::Expr { hir_id: self.next_id(), kind, span, attrs } + hir::Expr { hir_id: self.next_id(span), kind, span, attrs } } fn field(&mut self, ident: Ident, expr: &'hir hir::Expr<'hir>, span: Span) -> hir::Field<'hir> { - hir::Field { hir_id: self.next_id(), ident, span, expr, is_shorthand: false } + hir::Field { hir_id: self.next_id(span), ident, expr, is_shorthand: false } } fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> { - hir::Arm { - hir_id: self.next_id(), - attrs: &[], - pat, - guard: None, - span: expr.span, - body: expr, - } + hir::Arm { hir_id: self.next_id(expr.span), attrs: &[], pat, guard: None, body: expr } } } diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index eef6d38aa0584..cec4940f7ad20 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -13,7 +13,7 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::LocalDefId; use rustc_span::source_map::{respan, DesugaringKind}; use rustc_span::symbol::{kw, sym, Ident}; -use rustc_span::Span; +use rustc_span::{Span, DUMMY_SP}; use rustc_target::spec::abi; use smallvec::{smallvec, SmallVec}; @@ -34,8 +34,8 @@ impl ItemLowerer<'_, '_, '_> { } impl<'a> Visitor<'a> for ItemLowerer<'a, '_, '_> { - fn visit_mod(&mut self, m: &'a Mod, _s: Span, _attrs: &[Attribute], n: NodeId) { - let hir_id = self.lctx.lower_node_id(n); + fn visit_mod(&mut self, m: &'a Mod, span: Span, _attrs: &[Attribute], n: NodeId) { + let hir_id = self.lctx.lower_node_id(n, span); self.lctx.modules.insert( hir_id, @@ -230,14 +230,13 @@ impl<'hir> LoweringContext<'_, 'hir> { if let ItemKind::MacroDef(MacroDef { ref body, macro_rules }) = i.kind { if !macro_rules || self.sess.contains_name(&i.attrs, sym::macro_export) { - let hir_id = self.lower_node_id(i.id); + let hir_id = self.lower_node_id(i.id, i.span); let body = P(self.lower_mac_args(body)); self.exported_macros.push(hir::MacroDef { ident, vis, attrs, hir_id, - span: i.span, ast: MacroDef { body, macro_rules }, }); } else { @@ -248,7 +247,14 @@ impl<'hir> LoweringContext<'_, 'hir> { let kind = self.lower_item_kind(i.span, i.id, &mut ident, attrs, &mut vis, &i.kind); - Some(hir::Item { hir_id: self.lower_node_id(i.id), ident, attrs, kind, vis, span: i.span }) + Some(hir::Item { + hir_id: self.lower_node_id(i.id, i.span), + ident, + attrs, + kind, + vis, + span: i.span, + }) } fn lower_item_kind( @@ -357,14 +363,14 @@ impl<'hir> LoweringContext<'_, 'hir> { self.lower_generics(generics, ImplTraitContext::disallowed()), ), ItemKind::Struct(ref struct_def, ref generics) => { - let struct_def = self.lower_variant_data(struct_def); + let struct_def = self.lower_variant_data(span, struct_def); hir::ItemKind::Struct( struct_def, self.lower_generics(generics, ImplTraitContext::disallowed()), ) } ItemKind::Union(ref vdata, ref generics) => { - let vdata = self.lower_variant_data(vdata); + let vdata = self.lower_variant_data(span, vdata); hir::ItemKind::Union( vdata, self.lower_generics(generics, ImplTraitContext::disallowed()), @@ -395,7 +401,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // method, it will not be considered an in-band // lifetime to be added, but rather a reference to a // parent lifetime. - let lowered_trait_impl_id = self.lower_node_id(id); + let lowered_trait_impl_id = self.lower_node_id(id, DUMMY_SP); let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs( ast_generics, def_id, @@ -537,7 +543,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let span = path.span; self.with_hir_id_owner(new_node_id, |this| { - let new_id = this.lower_node_id(new_node_id); + let new_id = this.lower_node_id(new_node_id, span); let res = this.lower_res(res); let path = this.lower_path_extra(res, &path, ParamMode::Explicit, None); let kind = hir::ItemKind::Use(path, hir::UseKind::Single); @@ -594,7 +600,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // Add all the nested `PathListItem`s to the HIR. for &(ref use_tree, id) in trees { - let new_hir_id = self.lower_node_id(id); + let new_hir_id = self.lower_node_id(id, use_tree.span); let mut prefix = prefix.clone(); @@ -663,7 +669,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let segments = self.arena.alloc_from_iter(path.segments.iter().map(|seg| hir::PathSegment { ident: seg.ident, - hir_id: seg.hir_id.map(|_| self.next_id()), + hir_id: seg.hir_id.map(|_| self.next_id(seg.ident.span)), res: seg.res, args: None, infer_args: seg.infer_args, @@ -679,7 +685,7 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::VisibilityKind::Restricted { ref path, hir_id: _ } => { hir::VisibilityKind::Restricted { path: self.rebuild_use_path(path), - hir_id: self.next_id(), + hir_id: self.next_id(vis.span), } } }; @@ -689,7 +695,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem<'hir> { let def_id = self.resolver.local_def_id(i.id); hir::ForeignItem { - hir_id: self.lower_node_id(i.id), + hir_id: self.lower_node_id(i.id, i.span), ident: i.ident, attrs: self.lower_attrs(&i.attrs), kind: match i.kind { @@ -724,9 +730,8 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef<'hir> { hir::ForeignItemRef { - id: hir::ForeignItemId { hir_id: self.lower_node_id(i.id) }, + id: hir::ForeignItemId { hir_id: self.lower_node_id(i.id, i.span) }, ident: i.ident, - span: i.span, vis: self.lower_visibility(&i.vis, Some(i.id)), } } @@ -738,15 +743,14 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> { hir::Variant { attrs: self.lower_attrs(&v.attrs), - data: self.lower_variant_data(&v.data), + data: self.lower_variant_data(v.span, &v.data), disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)), - id: self.lower_node_id(v.id), + id: self.lower_node_id(v.id, v.span), ident: v.ident, - span: v.span, } } - fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData<'hir> { + fn lower_variant_data(&mut self, span: Span, vdata: &VariantData) -> hir::VariantData<'hir> { match *vdata { VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct( self.arena @@ -756,9 +760,9 @@ impl<'hir> LoweringContext<'_, 'hir> { VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple( self.arena .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_struct_field(f))), - self.lower_node_id(id), + self.lower_node_id(id, span), ), - VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id)), + VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id, span)), } } @@ -776,8 +780,7 @@ impl<'hir> LoweringContext<'_, 'hir> { self.lower_ty(&f.ty, ImplTraitContext::disallowed()) }; hir::StructField { - span: f.span, - hir_id: self.lower_node_id(f.id), + hir_id: self.lower_node_id(f.id, f.span), ident: match f.ident { Some(ident) => ident, // FIXME(jseyfried): positional field hygiene. @@ -824,7 +827,7 @@ impl<'hir> LoweringContext<'_, 'hir> { }; hir::TraitItem { - hir_id: self.lower_node_id(i.id), + hir_id: self.lower_node_id(i.id, i.span), ident: i.ident, attrs: self.lower_attrs(&i.attrs), generics, @@ -844,9 +847,9 @@ impl<'hir> LoweringContext<'_, 'hir> { } AssocItemKind::MacCall(..) => unimplemented!(), }; - let id = hir::TraitItemId { hir_id: self.lower_node_id(i.id) }; + let id = hir::TraitItemId { hir_id: self.lower_node_id(i.id, i.span) }; let defaultness = hir::Defaultness::Default { has_value: has_default }; - hir::TraitItemRef { id, ident: i.ident, span: i.span, defaultness, kind } + hir::TraitItemRef { id, ident: i.ident, defaultness, kind } } /// Construct `ExprKind::Err` for the given `span`. @@ -908,7 +911,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let has_value = true; let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value); hir::ImplItem { - hir_id: self.lower_node_id(i.id), + hir_id: self.lower_node_id(i.id, i.span), ident: i.ident, attrs: self.lower_attrs(&i.attrs), generics, @@ -924,9 +927,8 @@ impl<'hir> LoweringContext<'_, 'hir> { let has_value = true; let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value); hir::ImplItemRef { - id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) }, + id: hir::ImplItemId { hir_id: self.lower_node_id(i.id, i.span) }, ident: i.ident, - span: i.span, vis: self.lower_visibility(&i.vis, Some(i.id)), defaultness, kind: match &i.kind { @@ -956,9 +958,9 @@ impl<'hir> LoweringContext<'_, 'hir> { VisibilityKind::Restricted { ref path, id } => { debug!("lower_visibility: restricted path id = {:?}", id); let lowered_id = if let Some(owner) = explicit_owner { - self.lower_node_id_with_owner(id, owner) + self.lower_node_id_with_owner(id, owner, v.span) } else { - self.lower_node_id(id) + self.lower_node_id(id, v.span) }; let res = self.expect_full_res(id); let res = self.lower_res(res); @@ -1013,10 +1015,9 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> { hir::Param { attrs: self.lower_attrs(¶m.attrs), - hir_id: self.lower_node_id(param.id), + hir_id: self.lower_node_id(param.id, param.span), pat: self.lower_pat(¶m.pat), ty_span: param.ty.span, - span: param.span, } } @@ -1111,7 +1112,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // parameters (c.f. rust-lang/rust#64512). for (index, parameter) in decl.inputs.iter().enumerate() { let parameter = this.lower_param(parameter); - let span = parameter.pat.span; + let span = this.spans[parameter.pat.hir_id]; // Check if this is a binding pattern, if so, we can optimize and avoid adding a // `let = __argN;` statement. In this case, we do not rename the parameter. @@ -1153,7 +1154,6 @@ impl<'hir> LoweringContext<'_, 'hir> { hir_id: parameter.hir_id, pat: new_parameter_pat, ty_span: parameter.ty_span, - span: parameter.span, }; if is_simple_parameter { @@ -1463,7 +1463,7 @@ impl<'hir> LoweringContext<'_, 'hir> { }), WherePredicate::EqPredicate(WhereEqPredicate { id, ref lhs_ty, ref rhs_ty, span }) => { hir::WherePredicate::EqPredicate(hir::WhereEqPredicate { - hir_id: self.lower_node_id(id), + hir_id: self.lower_node_id(id, span), lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()), rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()), span, diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index f81dc39842cb9..25aac4a05b190 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -51,7 +51,7 @@ use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res}; use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX}; use rustc_hir::definitions::{DefKey, DefPathData, Definitions}; use rustc_hir::intravisit; -use rustc_hir::{ConstArg, GenericArg, ParamName}; +use rustc_hir::{ConstArg, GenericArg, HirIdVec, ParamName}; use rustc_index::vec::{Idx, IndexVec}; use rustc_session::lint::{builtin::BARE_TRAIT_OBJECTS, BuiltinLintDiagnostics, LintBuffer}; use rustc_session::parse::ParseSess; @@ -59,7 +59,7 @@ use rustc_session::Session; use rustc_span::hygiene::ExpnId; use rustc_span::source_map::{respan, DesugaringKind, ExpnData, ExpnKind}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::Span; +use rustc_span::{Span, DUMMY_SP}; use smallvec::{smallvec, SmallVec}; use std::collections::BTreeMap; @@ -110,6 +110,9 @@ struct LoweringContext<'a, 'hir: 'a> { modules: BTreeMap, + /// Collected spans from the AST. + spans: HirIdVec, + generator_kind: Option, /// When inside an `async` context, this is the `HirId` of the @@ -304,6 +307,7 @@ pub fn lower_crate<'a, 'hir>( bodies: BTreeMap::new(), trait_impls: BTreeMap::new(), modules: BTreeMap::new(), + spans: Default::default(), exported_macros: Vec::new(), non_exported_macro_attrs: Vec::new(), catch_scopes: Vec::new(), @@ -556,7 +560,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } } - self.lower_node_id(CRATE_NODE_ID); + self.lower_node_id(CRATE_NODE_ID, c.span); debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == Some(hir::CRATE_HIR_ID)); visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c); @@ -590,8 +594,12 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.resolver.definitions().init_def_id_to_hir_id_mapping(def_id_to_hir_id); + //FIXME(cjgillot) Ideally, each LocalDefId would be a HIR owner. + // In the mean time, allocate the missing empty vectors. + self.spans.push_owner(Idx::new(self.resolver.definitions().def_index_count() - 1)); + hir::Crate { - item: hir::CrateItem { module, attrs, span: c.span }, + item: hir::CrateItem { module, attrs }, exported_macros: self.arena.alloc_from_iter(self.exported_macros), non_exported_macro_attrs: self.arena.alloc_from_iter(self.non_exported_macro_attrs), items: self.items, @@ -604,6 +612,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { modules: self.modules, proc_macros, trait_map, + spans: self.spans, } } @@ -619,7 +628,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Set up the counter if needed. self.item_local_id_counters.entry(owner).or_insert(0); // Always allocate the first `HirId` for the owner itself. - let lowered = self.lower_node_id_with_owner(owner, owner); + let lowered = self.lower_node_id_with_owner(owner, owner, DUMMY_SP); debug_assert_eq!(lowered.local_id.as_u32(), 0); lowered } @@ -627,6 +636,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { fn lower_node_id_generic( &mut self, ast_node_id: NodeId, + span: Span, alloc_hir_id: impl FnOnce(&mut Self) -> hir::HirId, ) -> hir::HirId { assert_ne!(ast_node_id, DUMMY_NODE_ID); @@ -637,15 +647,27 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.node_id_to_hir_id.resize(min_size, None); } - if let Some(existing_hir_id) = self.node_id_to_hir_id[ast_node_id] { + let hir_id = if let Some(existing_hir_id) = self.node_id_to_hir_id[ast_node_id] { + if span != DUMMY_SP { + // Some HIR owners are lowered before the traversal of the AST. + // They use DUMMY_SP as a placeholder, to be overwritten here. + #[cfg(debug_assertions)] + if self.spans[existing_hir_id] != DUMMY_SP { + assert_eq!(self.spans[existing_hir_id], span); + } + self.spans[existing_hir_id] = span; + } existing_hir_id } else { // Generate a new `HirId`. let hir_id = alloc_hir_id(self); self.node_id_to_hir_id[ast_node_id] = Some(hir_id); + self.spans.push(hir_id, span); hir_id - } + }; + + hir_id } fn with_hir_id_owner(&mut self, owner: NodeId, f: impl FnOnce(&mut Self) -> T) -> T { @@ -672,8 +694,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { /// actually used in the HIR, as that would trigger an assertion in the /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped /// properly. Calling the method twice with the same `NodeId` is fine though. - fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId { - self.lower_node_id_generic(ast_node_id, |this| { + fn lower_node_id(&mut self, ast_node_id: NodeId, span: Span) -> hir::HirId { + self.lower_node_id_generic(ast_node_id, span, |this| { let &mut (owner, ref mut local_id_counter) = this.current_hir_id_owner.last_mut().unwrap(); let local_id = *local_id_counter; @@ -682,8 +704,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }) } - fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId { - self.lower_node_id_generic(ast_node_id, |this| { + fn lower_node_id_with_owner( + &mut self, + ast_node_id: NodeId, + owner: NodeId, + span: Span, + ) -> hir::HirId { + self.lower_node_id_generic(ast_node_id, span, |this| { let local_id_counter = this .item_local_id_counters .get_mut(&owner) @@ -705,14 +732,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }) } - fn next_id(&mut self) -> hir::HirId { + fn next_id(&mut self, span: Span) -> hir::HirId { let node_id = self.resolver.next_node_id(); - self.lower_node_id(node_id) + self.lower_node_id(node_id, span) } fn lower_res(&mut self, res: Res) -> Res { res.map_id(|id| { - self.lower_node_id_generic(id, |_| { + self.lower_node_id_generic(id, DUMMY_SP, |_| { panic!("expected `NodeId` to be lowered already for res {:#?}", res); }) }) @@ -834,11 +861,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ); hir::GenericParam { - hir_id: self.lower_node_id(node_id), + hir_id: self.lower_node_id(node_id, span), name: hir_name, attrs: &[], bounds: &[], - span, pure_wrt_drop: false, kind: hir::GenericParamKind::Lifetime { kind }, } @@ -1159,10 +1185,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }; hir::TypeBinding { - hir_id: self.lower_node_id(constraint.id), + hir_id: self.lower_node_id(constraint.id, constraint.span), ident: constraint.ident, kind, - span: constraint.span, } } @@ -1209,20 +1234,19 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { tokens: None, }; - let ct = self.with_new_scopes(|this| hir::AnonConst { - hir_id: this.lower_node_id(node_id), - body: this.lower_const_body(path_expr.span, Some(&path_expr)), + let ct = self.lower_anon_const(&AnonConst { + id: node_id, + value: rustc_ast::ptr::P(path_expr), }); - return GenericArg::Const(ConstArg { value: ct, span: ty.span }); + return GenericArg::Const(ConstArg { value: ct }); } } } GenericArg::Type(self.lower_ty_direct(&ty, itctx)) } - ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg { - value: self.lower_anon_const(&ct), - span: ct.value.span, - }), + ast::GenericArg::Const(ct) => { + GenericArg::Const(ConstArg { value: self.lower_anon_const(&ct) }) + } } } @@ -1238,7 +1262,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { param_mode: ParamMode, itctx: ImplTraitContext<'_, 'hir>, ) -> hir::Ty<'hir> { - let id = self.lower_node_id(t.id); + let id = self.lower_node_id(t.id, t.span); let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx); let ty = self.ty_path(id, t.span, qpath); if let hir::TyKind::TraitObject(..) = ty.kind { @@ -1248,7 +1272,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> { - hir::Ty { hir_id: self.next_id(), kind, span } + hir::Ty { hir_id: self.next_id(span), kind, span } } fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> { @@ -1391,12 +1415,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Set the name to `impl Bound1 + Bound2`. let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span); in_band_ty_params.push(hir::GenericParam { - hir_id: self.lower_node_id(def_node_id), + hir_id: self.lower_node_id(def_node_id, span), name: ParamName::Plain(ident), pure_wrt_drop: false, attrs: &[], bounds: hir_bounds, - span, kind: hir::GenericParamKind::Type { default: None, synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), @@ -1446,7 +1469,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } }; - hir::Ty { kind, span: t.span, hir_id: self.lower_node_id(t.id) } + hir::Ty { kind, span: t.span, hir_id: self.lower_node_id(t.id, t.span) } } fn lower_opaque_impl_trait( @@ -1518,7 +1541,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { opaque_ty_span: Span, ) -> hir::HirId { let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item); - let opaque_ty_id = self.lower_node_id(opaque_ty_node_id); + let opaque_ty_id = self.lower_node_id(opaque_ty_node_id, opaque_ty_span); // Generate an `type Foo = impl Trait;` declaration. trace!("registering opaque type with id {:#?}", opaque_ty_id); let opaque_ty_item = hir::Item { @@ -1573,15 +1596,15 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { intravisit::NestedVisitorMap::None } - fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs<'v>) { + fn visit_generic_args(&mut self, parameters: &'v hir::GenericArgs<'v>) { // Don't collect elided lifetimes used inside of `Fn()` syntax. if parameters.parenthesized { let old_collect_elided_lifetimes = self.collect_elided_lifetimes; self.collect_elided_lifetimes = false; - intravisit::walk_generic_args(self, span, parameters); + intravisit::walk_generic_args(self, parameters); self.collect_elided_lifetimes = old_collect_elided_lifetimes; } else { - intravisit::walk_generic_args(self, span, parameters); + intravisit::walk_generic_args(self, parameters); } } @@ -1654,14 +1677,17 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.already_defined_lifetimes.insert(name); self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime { - hir_id: self.context.next_id(), + hir_id: self.context.next_id(lifetime.span), span: lifetime.span, name, })); let def_node_id = self.context.resolver.next_node_id(); - let hir_id = - self.context.lower_node_id_with_owner(def_node_id, self.opaque_ty_id); + let hir_id = self.context.lower_node_id_with_owner( + def_node_id, + self.opaque_ty_id, + lifetime.span, + ); self.context.resolver.create_def( self.parent, def_node_id, @@ -1684,7 +1710,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.output_lifetime_params.push(hir::GenericParam { hir_id, name, - span: lifetime.span, pure_wrt_drop: false, attrs: &[], bounds: &[], @@ -1745,11 +1770,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let init = l.init.as_ref().map(|e| self.lower_expr(e)); ( hir::Local { - hir_id: self.lower_node_id(l.id), + hir_id: self.lower_node_id(l.id, l.span), ty, pat: self.lower_pat(&l.pat), init, - span: l.span, attrs: l.attrs.iter().map(|a| self.lower_attr(a)).collect::>().into(), source: hir::LocalSource::Normal, }, @@ -2041,7 +2065,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { |&(span, hir_name)| { // Input lifetime like `'a` or `'1`: GenericArg::Lifetime(hir::Lifetime { - hir_id: self.next_id(), + hir_id: self.next_id(span), span, name: hir::LifetimeName::Param(hir_name), }) @@ -2050,7 +2074,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { generic_args.extend(lifetime_params[input_lifetimes_count..].iter().map(|&(span, _)| // Output lifetime like `'_`. GenericArg::Lifetime(hir::Lifetime { - hir_id: self.next_id(), + hir_id: self.next_id(span), span, name: hir::LifetimeName::Implicit, }))); @@ -2098,7 +2122,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // ::std::future::Future hir::LangItem::Future, span, - self.next_id(), + self.next_id(span), future_args, ) } @@ -2151,7 +2175,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { span: Span, name: hir::LifetimeName, ) -> hir::Lifetime { - hir::Lifetime { hir_id: self.lower_node_id(id), span, name } + hir::Lifetime { hir_id: self.lower_node_id(id, span), span, name } } fn lower_generic_params_mut<'s>( @@ -2254,9 +2278,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }; hir::GenericParam { - hir_id: self.lower_node_id(param.id), + hir_id: self.lower_node_id(param.id, param.ident.span), name, - span: param.ident.span, pure_wrt_drop: self.sess.contains_name(¶m.attrs, sym::may_dangle), attrs: self.lower_attrs(¶m.attrs), bounds: self.arena.alloc_from_iter(bounds), @@ -2273,7 +2296,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { hir::QPath::Resolved(None, path) => path, qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath), }; - hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) } + hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id, path.span) } } fn lower_poly_trait_ref( @@ -2359,9 +2382,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { .flatten(), ); let rules = self.lower_block_check_mode(&b.rules); - let hir_id = self.lower_node_id(b.id); + let hir_id = self.lower_node_id(b.id, b.span); - hir::Block { hir_id, stmts, expr, rules, span: b.span, targeted_by_break } + hir::Block { hir_id, stmts, expr, rules, targeted_by_break } } /// Lowers a block directly to an expression, presuming that it @@ -2372,9 +2395,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst { - self.with_new_scopes(|this| hir::AnonConst { - hir_id: this.lower_node_id(c.id), - body: this.lower_const_body(c.value.span, Some(&c.value)), + self.with_new_scopes(|this| { + let body = this.lower_const_body(c.value.span, Some(&c.value)); + let span = this.bodies[&body].value.span; + hir::AnonConst { hir_id: this.lower_node_id(c.id, span), body } }) } @@ -2385,15 +2409,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let mut ids: SmallVec<[hir::Stmt<'hir>; 1]> = item_ids .into_iter() .map(|item_id| { - let item_id = hir::ItemId { id: self.lower_node_id(item_id) }; + let item_id = hir::ItemId { id: self.lower_node_id(item_id, DUMMY_SP) }; self.stmt(s.span, hir::StmtKind::Item(item_id)) }) .collect(); ids.push({ hir::Stmt { - hir_id: self.lower_node_id(s.id), + hir_id: self.lower_node_id(s.id, s.span), kind: hir::StmtKind::Local(self.arena.alloc(l)), - span: s.span, } }); return ids; @@ -2407,10 +2430,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { .map(|item_id| { let hir_id = id .take() - .map(|id| self.lower_node_id(id)) - .unwrap_or_else(|| self.next_id()); + .map(|id| self.lower_node_id(id, s.span)) + .unwrap_or_else(|| self.next_id(s.span)); - hir::Stmt { hir_id, kind: hir::StmtKind::Item(item_id), span: s.span } + hir::Stmt { hir_id, kind: hir::StmtKind::Item(item_id) } }) .collect(); } @@ -2419,7 +2442,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { StmtKind::Empty => return smallvec![], StmtKind::MacCall(..) => panic!("shouldn't exist here"), }; - smallvec![hir::Stmt { hir_id: self.lower_node_id(s.id), kind, span: s.span }] + smallvec![hir::Stmt { hir_id: self.lower_node_id(s.id, s.span), kind }] } fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode { @@ -2454,7 +2477,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Helper methods for building HIR. fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> { - hir::Stmt { span, kind, hir_id: self.next_id() } + hir::Stmt { kind, hir_id: self.next_id(span) } } fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> { @@ -2469,7 +2492,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { pat: &'hir hir::Pat<'hir>, source: hir::LocalSource, ) -> hir::Stmt<'hir> { - let local = hir::Local { attrs, hir_id: self.next_id(), init, pat, source, span, ty: None }; + let local = hir::Local { attrs, hir_id: self.next_id(span), init, pat, source, ty: None }; self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local))) } @@ -2486,9 +2509,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let blk = hir::Block { stmts, expr, - hir_id: self.next_id(), + hir_id: self.next_id(span), rules: hir::BlockCheckMode::DefaultBlock, - span, targeted_by_break: false, }; self.arena.alloc(blk) @@ -2525,11 +2547,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { pat: &'hir hir::Pat<'hir>, ) -> &'hir [hir::FieldPat<'hir>] { let field = hir::FieldPat { - hir_id: self.next_id(), + hir_id: self.next_id(span), ident: Ident::new(sym::integer(0), span), is_shorthand: false, pat, - span, }; arena_vec![self; field] } @@ -2554,13 +2575,12 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ident: Ident, bm: hir::BindingAnnotation, ) -> (&'hir hir::Pat<'hir>, hir::HirId) { - let hir_id = self.next_id(); + let hir_id = self.next_id(span); ( self.arena.alloc(hir::Pat { hir_id, kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None), - span, default_binding_modes: true, }), hir_id, @@ -2572,19 +2592,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> { - self.arena.alloc(hir::Pat { - hir_id: self.next_id(), - kind, - span, - default_binding_modes: true, - }) + self.arena.alloc(hir::Pat { hir_id: self.next_id(span), kind, default_binding_modes: true }) } fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> { self.arena.alloc(hir::Pat { - hir_id: self.next_id(), + hir_id: self.next_id(span), kind, - span, default_binding_modes: false, }) } @@ -2608,7 +2622,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // The original ID is taken by the `PolyTraitRef`, // so the `Ty` itself needs a different one. - hir_id = self.next_id(); + hir_id = self.next_id(span); hir::TyKind::TraitObject( arena_vec![self; principal], self.elided_dyn_bound(span), @@ -2634,7 +2648,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { AnonymousLifetimeMode::CreateParameter => { let fresh_name = self.collect_fresh_in_band_lifetime(span); hir::Lifetime { - hir_id: self.next_id(), + hir_id: self.next_id(span), span, name: hir::LifetimeName::Param(fresh_name), } @@ -2729,7 +2743,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } let r = hir::Lifetime { - hir_id: self.next_id(), + hir_id: self.next_id(span), span, name: hir::LifetimeName::ImplicitObjectLifetimeDefault, }; @@ -2738,7 +2752,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime { - hir::Lifetime { hir_id: self.next_id(), span, name: hir::LifetimeName::Implicit } + hir::Lifetime { hir_id: self.next_id(span), span, name: hir::LifetimeName::Implicit } } fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) { diff --git a/compiler/rustc_ast_lowering/src/pat.rs b/compiler/rustc_ast_lowering/src/pat.rs index e4e7b24d29e52..440268ccde85e 100644 --- a/compiler/rustc_ast_lowering/src/pat.rs +++ b/compiler/rustc_ast_lowering/src/pat.rs @@ -57,11 +57,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ); let fs = self.arena.alloc_from_iter(fields.iter().map(|f| hir::FieldPat { - hir_id: self.next_id(), + hir_id: self.next_id(f.span), ident: f.ident, pat: self.lower_pat(&f.pat), is_shorthand: f.is_shorthand, - span: f.span, })); break hir::PatKind::Struct(qpath, fs, etc); } @@ -242,7 +241,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { hir::PatKind::Binding( self.lower_binding_mode(binding_mode), - self.lower_node_id(canonical_id), + self.lower_node_id(canonical_id, rustc_span::DUMMY_SP), ident, lower_sub(self), ) @@ -274,9 +273,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { /// Construct a `Pat` with the `HirId` of `p.id` lowered. fn pat_with_node_id_of(&mut self, p: &Pat, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> { self.arena.alloc(hir::Pat { - hir_id: self.lower_node_id(p.id), + hir_id: self.lower_node_id(p.id, p.span), kind, - span: p.span, default_binding_modes: true, }) } diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index 6afed355dc338..2c1191c65051b 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -126,7 +126,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Otherwise, the base path is an implicit `Self` type path, // e.g., `Vec` in `Vec::new` or `::Item` in // `::Item::default`. - let new_id = self.next_id(); + let new_id = self.next_id(p.span); self.arena.alloc(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))) }; @@ -158,7 +158,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } // Wrap the associated extension in another type node. - let new_id = self.next_id(); + let new_id = self.next_id(p.span); ty = self.arena.alloc(self.ty_path(new_id, p.span, qpath)); } @@ -266,10 +266,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_))); let first_generic_span = generic_args .args - .iter() - .map(|a| a.span()) - .chain(generic_args.bindings.iter().map(|b| b.span)) - .next(); + .first() + .map(|a| self.spans[a.id()]) + .or_else(|| generic_args.bindings.first().map(|b| self.spans[b.hir_id])); if !generic_args.parenthesized && !has_lifetimes { generic_args.args = self .elided_path_lifetimes( @@ -340,9 +339,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let res = self.expect_full_res(segment.id); let id = if let Some(owner) = explicit_owner { - self.lower_node_id_with_owner(segment.id, owner) + self.lower_node_id_with_owner(segment.id, owner, segment.ident.span) } else { - self.lower_node_id(segment.id) + self.lower_node_id(segment.id, segment.ident.span) }; debug!( "lower_path_segment: ident={:?} original-id={:?} new-id={:?}", @@ -426,6 +425,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ) -> hir::TypeBinding<'hir> { let ident = Ident::with_dummy_span(hir::FN_OUTPUT_NAME); let kind = hir::TypeBindingKind::Equality { ty }; - hir::TypeBinding { hir_id: self.next_id(), span, ident, kind } + hir::TypeBinding { hir_id: self.next_id(span), ident, kind } } } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index acd254ae85cb1..a6f00fdb1e6a2 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1,6 +1,7 @@ use crate::def::{DefKind, Namespace, Res}; use crate::def_id::DefId; crate use crate::hir_id::HirId; +use crate::hir_id::HirIdVec; use crate::{itemlikevisit, LangItem}; use rustc_ast::util::parser::ExprPrecedence; @@ -14,7 +15,7 @@ use rustc_macros::HashStable_Generic; use rustc_span::def_id::LocalDefId; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{MultiSpan, Span, DUMMY_SP}; +use rustc_span::{Span, DUMMY_SP}; use rustc_target::asm::InlineAsmRegOrRegClass; use rustc_target::spec::abi::Abi; @@ -244,7 +245,6 @@ impl<'hir> PathSegment<'hir> { #[derive(Encodable, Debug, HashStable_Generic)] pub struct ConstArg { pub value: AnonConst, - pub span: Span, } #[derive(Debug, HashStable_Generic)] @@ -255,14 +255,6 @@ pub enum GenericArg<'hir> { } impl GenericArg<'_> { - pub fn span(&self) -> Span { - match self { - GenericArg::Lifetime(l) => l.span, - GenericArg::Type(t) => t.span, - GenericArg::Const(c) => c.span, - } - } - pub fn id(&self) -> HirId { match self { GenericArg::Lifetime(l) => l.hir_id, @@ -437,7 +429,6 @@ pub struct GenericParam<'hir> { pub name: ParamName, pub attrs: &'hir [Attribute], pub bounds: GenericBounds<'hir>, - pub span: Span, pub pure_wrt_drop: bool, pub kind: GenericParamKind<'hir>, } @@ -485,14 +476,6 @@ impl Generics<'hir> { } None } - - pub fn spans(&self) -> MultiSpan { - if self.params.is_empty() { - self.span.into() - } else { - self.params.iter().map(|p| p.span).collect::>().into() - } - } } /// Synthetic type parameters are converted to another form during lowering; this allows @@ -597,7 +580,6 @@ pub struct ModuleItems { pub struct CrateItem<'hir> { pub module: Mod<'hir>, pub attrs: &'hir [Attribute], - pub span: Span, } /// The top-level data structure that stores the entire contents of @@ -641,6 +623,9 @@ pub struct Crate<'hir> { pub proc_macros: Vec, pub trait_map: BTreeMap>, + + /// Collected spans from the AST. + pub spans: HirIdVec, } impl Crate<'hir> { @@ -734,7 +719,6 @@ pub struct MacroDef<'hir> { pub vis: Visibility<'hir>, pub attrs: &'hir [Attribute], pub hir_id: HirId, - pub span: Span, pub ast: ast::MacroDef, } @@ -752,7 +736,6 @@ pub struct Block<'hir> { pub hir_id: HirId, /// Distinguishes between `unsafe { ... }` and `{ ... }`. pub rules: BlockCheckMode, - pub span: Span, /// If true, then there may exist `break 'a` values that aim to /// break out of this block early. /// Used by `'label: {}` blocks and by `try {}` blocks. @@ -764,7 +747,6 @@ pub struct Pat<'hir> { #[stable_hasher(ignore)] pub hir_id: HirId, pub kind: PatKind<'hir>, - pub span: Span, // Whether to use default binding modes. // At present, this is false only for destructuring assignment. pub default_binding_modes: bool, @@ -850,7 +832,6 @@ pub struct FieldPat<'hir> { /// The pattern the field is destructured to. pub pat: &'hir Pat<'hir>, pub is_shorthand: bool, - pub span: Span, } /// Explicit binding annotations given in the HIR for a binding. Note @@ -1106,7 +1087,6 @@ impl UnOp { pub struct Stmt<'hir> { pub hir_id: HirId, pub kind: StmtKind<'hir>, - pub span: Span, } /// The contents of a statement. @@ -1144,7 +1124,6 @@ pub struct Local<'hir> { /// Initializer expression to set the value, if any. pub init: Option<&'hir Expr<'hir>>, pub hir_id: HirId, - pub span: Span, pub attrs: AttrVec, /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop /// desugaring. Otherwise will be `Normal`. @@ -1157,7 +1136,6 @@ pub struct Local<'hir> { pub struct Arm<'hir> { #[stable_hasher(ignore)] pub hir_id: HirId, - pub span: Span, pub attrs: &'hir [Attribute], /// If this pattern and the optional guard matches, then `body` is evaluated. pub pat: &'hir Pat<'hir>, @@ -1179,7 +1157,6 @@ pub struct Field<'hir> { pub hir_id: HirId, pub ident: Ident, pub expr: &'hir Expr<'hir>, - pub span: Span, pub is_shorthand: bool, } @@ -1977,7 +1954,6 @@ pub struct TypeBinding<'hir> { #[stable_hasher(project(name))] pub ident: Ident, pub kind: TypeBindingKind<'hir>, - pub span: Span, } // Represents the two kinds of type bindings. @@ -2198,7 +2174,6 @@ pub struct Param<'hir> { pub hir_id: HirId, pub pat: &'hir Pat<'hir>, pub ty_span: Span, - pub span: Span, } /// Represents the header (not the body) of a function declaration. @@ -2320,8 +2295,6 @@ pub struct Variant<'hir> { pub data: VariantData<'hir>, /// Explicit discriminant (e.g., `Foo = 1`). pub disr_expr: Option, - /// Span - pub span: Span, } #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] @@ -2401,7 +2374,6 @@ impl VisibilityKind<'_> { #[derive(Debug, HashStable_Generic)] pub struct StructField<'hir> { - pub span: Span, #[stable_hasher(project(name))] pub ident: Ident, pub vis: Visibility<'hir>, @@ -2608,7 +2580,6 @@ pub struct TraitItemRef { #[stable_hasher(project(name))] pub ident: Ident, pub kind: AssocItemKind, - pub span: Span, pub defaultness: Defaultness, } @@ -2624,7 +2595,6 @@ pub struct ImplItemRef<'hir> { #[stable_hasher(project(name))] pub ident: Ident, pub kind: AssocItemKind, - pub span: Span, pub vis: Visibility<'hir>, pub defaultness: Defaultness, } @@ -2655,7 +2625,6 @@ pub struct ForeignItemRef<'hir> { pub id: ForeignItemId, #[stable_hasher(project(name))] pub ident: Ident, - pub span: Span, pub vis: Visibility<'hir>, } diff --git a/compiler/rustc_hir/src/hir_id.rs b/compiler/rustc_hir/src/hir_id.rs index cc8ac4cf5be51..a230bde8be001 100644 --- a/compiler/rustc_hir/src/hir_id.rs +++ b/compiler/rustc_hir/src/hir_id.rs @@ -1,4 +1,5 @@ use crate::def_id::{LocalDefId, CRATE_DEF_INDEX}; +use rustc_index::vec::IndexVec; use std::fmt; /// Uniquely identifies a node in the HIR of the current crate. It is @@ -45,3 +46,45 @@ pub const CRATE_HIR_ID: HirId = HirId { owner: LocalDefId { local_def_index: CRATE_DEF_INDEX }, local_id: ItemLocalId::from_u32(0), }; + +#[derive(Clone, Default, Debug, Encodable, Decodable)] +pub struct HirIdVec { + map: IndexVec>, +} + +impl HirIdVec { + pub fn push_owner(&mut self, id: LocalDefId) { + self.map.ensure_contains_elem(id, IndexVec::new); + } + + pub fn push(&mut self, id: HirId, value: T) { + if id.local_id == ItemLocalId::from_u32(0) { + self.push_owner(id.owner); + } + let submap = &mut self.map[id.owner]; + let _ret_id = submap.push(value); + debug_assert_eq!(_ret_id, id.local_id); + } + + pub fn get(&self, id: HirId) -> Option<&T> { + self.map.get(id.owner)?.get(id.local_id) + } + + pub fn get_owner(&self, id: LocalDefId) -> &IndexVec { + &self.map[id] + } +} + +impl std::ops::Index for HirIdVec { + type Output = T; + + fn index(&self, id: HirId) -> &T { + &self.map[id.owner][id.local_id] + } +} + +impl std::ops::IndexMut for HirIdVec { + fn index_mut(&mut self, id: HirId) -> &mut T { + &mut self.map[id.owner][id.local_id] + } +} diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index b0e82214cf95f..04d401f3d58ce 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -37,7 +37,6 @@ use crate::itemlikevisit::{ItemLikeVisitor, ParItemLikeVisitor}; use rustc_ast::walk_list; use rustc_ast::{Attribute, Label}; use rustc_span::symbol::{Ident, Symbol}; -use rustc_span::Span; pub struct DeepVisitor<'v, V> { visitor: &'v mut V, @@ -335,13 +334,13 @@ pub trait Visitor<'v>: Sized { fn visit_id(&mut self, _hir_id: HirId) { // Nothing to do. } - fn visit_name(&mut self, _span: Span, _name: Symbol) { + fn visit_name(&mut self, _name: Symbol) { // Nothing to do. } fn visit_ident(&mut self, ident: Ident) { walk_ident(self, ident) } - fn visit_mod(&mut self, m: &'v Mod<'v>, _s: Span, n: HirId) { + fn visit_mod(&mut self, m: &'v Mod<'v>, n: HirId) { walk_mod(self, m, n) } fn visit_foreign_item(&mut self, i: &'v ForeignItem<'v>) { @@ -383,8 +382,8 @@ pub trait Visitor<'v>: Sized { fn visit_fn_decl(&mut self, fd: &'v FnDecl<'v>) { walk_fn_decl(self, fd) } - fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl<'v>, b: BodyId, s: Span, id: HirId) { - walk_fn(self, fk, fd, b, s, id) + fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl<'v>, b: BodyId, id: HirId) { + walk_fn(self, fk, fd, b, id) } fn visit_use(&mut self, path: &'v Path<'v>, hir_id: HirId) { walk_use(self, path, hir_id) @@ -419,7 +418,6 @@ pub trait Visitor<'v>: Sized { _: Symbol, _: &'v Generics<'v>, _parent_id: HirId, - _: Span, ) { walk_struct_def(self, s) } @@ -431,7 +429,6 @@ pub trait Visitor<'v>: Sized { enum_definition: &'v EnumDef<'v>, generics: &'v Generics<'v>, item_id: HirId, - _: Span, ) { walk_enum_def(self, enum_definition, generics, item_id) } @@ -451,17 +448,17 @@ pub trait Visitor<'v>: Sized { fn visit_lifetime(&mut self, lifetime: &'v Lifetime) { walk_lifetime(self, lifetime) } - fn visit_qpath(&mut self, qpath: &'v QPath<'v>, id: HirId, span: Span) { - walk_qpath(self, qpath, id, span) + fn visit_qpath(&mut self, qpath: &'v QPath<'v>, id: HirId) { + walk_qpath(self, qpath, id) } fn visit_path(&mut self, path: &'v Path<'v>, _id: HirId) { walk_path(self, path) } - fn visit_path_segment(&mut self, path_span: Span, path_segment: &'v PathSegment<'v>) { - walk_path_segment(self, path_span, path_segment) + fn visit_path_segment(&mut self, path_segment: &'v PathSegment<'v>) { + walk_path_segment(self, path_segment) } - fn visit_generic_args(&mut self, path_span: Span, generic_args: &'v GenericArgs<'v>) { - walk_generic_args(self, path_span, generic_args) + fn visit_generic_args(&mut self, generic_args: &'v GenericArgs<'v>) { + walk_generic_args(self, generic_args) } fn visit_assoc_type_binding(&mut self, type_binding: &'v TypeBinding<'v>) { walk_assoc_type_binding(self, type_binding) @@ -483,7 +480,7 @@ pub trait Visitor<'v>: Sized { /// Walks the contents of a crate. See also `Crate::visit_all_items`. pub fn walk_crate<'v, V: Visitor<'v>>(visitor: &mut V, krate: &'v Crate<'v>) { - visitor.visit_mod(&krate.item.module, krate.item.span, CRATE_HIR_ID); + visitor.visit_mod(&krate.item.module, CRATE_HIR_ID); walk_list!(visitor, visit_attribute, krate.item.attrs); walk_list!(visitor, visit_macro_def, krate.exported_macros); } @@ -517,7 +514,7 @@ pub fn walk_local<'v, V: Visitor<'v>>(visitor: &mut V, local: &'v Local<'v>) { } pub fn walk_ident<'v, V: Visitor<'v>>(visitor: &mut V, ident: Ident) { - visitor.visit_name(ident.span, ident.name); + visitor.visit_name(ident.name); } pub fn walk_label<'v, V: Visitor<'v>>(visitor: &mut V, label: &'v Label) { @@ -567,7 +564,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) { ItemKind::ExternCrate(orig_name) => { visitor.visit_id(item.hir_id); if let Some(orig_name) = orig_name { - visitor.visit_name(item.span, orig_name); + visitor.visit_name(orig_name); } } ItemKind::Use(ref path, _) => { @@ -582,12 +579,11 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) { FnKind::ItemFn(item.ident, generics, sig.header, &item.vis, &item.attrs), &sig.decl, body_id, - item.span, item.hir_id, ), ItemKind::Mod(ref module) => { // `visit_mod()` takes care of visiting the `Item`'s `HirId`. - visitor.visit_mod(module, item.span, item.hir_id) + visitor.visit_mod(module, item.hir_id) } ItemKind::ForeignMod { abi: _, items } => { visitor.visit_id(item.hir_id); @@ -609,7 +605,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) { ItemKind::Enum(ref enum_definition, ref generics) => { visitor.visit_generics(generics); // `visit_enum_def()` takes care of visiting the `Item`'s `HirId`. - visitor.visit_enum_def(enum_definition, generics, item.hir_id, item.span) + visitor.visit_enum_def(enum_definition, generics, item.hir_id) } ItemKind::Impl { unsafety: _, @@ -632,13 +628,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) { | ItemKind::Union(ref struct_definition, ref generics) => { visitor.visit_generics(generics); visitor.visit_id(item.hir_id); - visitor.visit_variant_data( - struct_definition, - item.ident.name, - generics, - item.hir_id, - item.span, - ); + visitor.visit_variant_data(struct_definition, item.ident.name, generics, item.hir_id); } ItemKind::Trait(.., ref generics, bounds, trait_item_refs) => { visitor.visit_id(item.hir_id); @@ -678,13 +668,7 @@ pub fn walk_variant<'v, V: Visitor<'v>>( ) { visitor.visit_ident(variant.ident); visitor.visit_id(variant.id); - visitor.visit_variant_data( - &variant.data, - variant.ident.name, - generics, - parent_item_id, - variant.span, - ); + visitor.visit_variant_data(&variant.data, variant.ident.name, generics, parent_item_id); walk_list!(visitor, visit_anon_const, &variant.disr_expr); walk_list!(visitor, visit_attribute, variant.attrs); } @@ -708,7 +692,7 @@ pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v>) { visitor.visit_fn_decl(&function_declaration.decl); } TyKind::Path(ref qpath) => { - visitor.visit_qpath(qpath, typ.hir_id, typ.span); + visitor.visit_qpath(qpath, typ.hir_id); } TyKind::OpaqueDef(item_id, lifetimes) => { visitor.visit_nested_item(item_id); @@ -729,12 +713,7 @@ pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v>) { } } -pub fn walk_qpath<'v, V: Visitor<'v>>( - visitor: &mut V, - qpath: &'v QPath<'v>, - id: HirId, - span: Span, -) { +pub fn walk_qpath<'v, V: Visitor<'v>>(visitor: &mut V, qpath: &'v QPath<'v>, id: HirId) { match *qpath { QPath::Resolved(ref maybe_qself, ref path) => { walk_list!(visitor, visit_ty, maybe_qself); @@ -742,7 +721,7 @@ pub fn walk_qpath<'v, V: Visitor<'v>>( } QPath::TypeRelative(ref qself, ref segment) => { visitor.visit_ty(qself); - visitor.visit_path_segment(span, segment); + visitor.visit_path_segment(segment); } QPath::LangItem(..) => {} } @@ -750,27 +729,19 @@ pub fn walk_qpath<'v, V: Visitor<'v>>( pub fn walk_path<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path<'v>) { for segment in path.segments { - visitor.visit_path_segment(path.span, segment); + visitor.visit_path_segment(segment); } } -pub fn walk_path_segment<'v, V: Visitor<'v>>( - visitor: &mut V, - path_span: Span, - segment: &'v PathSegment<'v>, -) { +pub fn walk_path_segment<'v, V: Visitor<'v>>(visitor: &mut V, segment: &'v PathSegment<'v>) { visitor.visit_ident(segment.ident); walk_list!(visitor, visit_id, segment.hir_id); if let Some(ref args) = segment.args { - visitor.visit_generic_args(path_span, args); + visitor.visit_generic_args(args); } } -pub fn walk_generic_args<'v, V: Visitor<'v>>( - visitor: &mut V, - _path_span: Span, - generic_args: &'v GenericArgs<'v>, -) { +pub fn walk_generic_args<'v, V: Visitor<'v>>(visitor: &mut V, generic_args: &'v GenericArgs<'v>) { walk_list!(visitor, visit_generic_arg, generic_args.args); walk_list!(visitor, visit_assoc_type_binding, generic_args.bindings); } @@ -795,14 +766,14 @@ pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat<'v>) { visitor.visit_id(pattern.hir_id); match pattern.kind { PatKind::TupleStruct(ref qpath, children, _) => { - visitor.visit_qpath(qpath, pattern.hir_id, pattern.span); + visitor.visit_qpath(qpath, pattern.hir_id); walk_list!(visitor, visit_pat, children); } PatKind::Path(ref qpath) => { - visitor.visit_qpath(qpath, pattern.hir_id, pattern.span); + visitor.visit_qpath(qpath, pattern.hir_id); } PatKind::Struct(ref qpath, fields, _) => { - visitor.visit_qpath(qpath, pattern.hir_id, pattern.span); + visitor.visit_qpath(qpath, pattern.hir_id); for field in fields { visitor.visit_id(field.hir_id); visitor.visit_ident(field.ident); @@ -859,9 +830,9 @@ pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v GenericB GenericBound::Trait(ref typ, modifier) => { visitor.visit_poly_trait_ref(typ, modifier); } - GenericBound::LangItemTrait(_, span, hir_id, args) => { + GenericBound::LangItemTrait(_, _, hir_id, args) => { visitor.visit_id(hir_id); - visitor.visit_generic_args(span, args); + visitor.visit_generic_args(args); } GenericBound::Outlives(ref lifetime) => visitor.visit_lifetime(lifetime), } @@ -948,7 +919,6 @@ pub fn walk_fn<'v, V: Visitor<'v>>( function_kind: FnKind<'v>, function_declaration: &'v FnDecl<'v>, body_id: BodyId, - _span: Span, id: HirId, ) { visitor.visit_id(id); @@ -979,7 +949,6 @@ pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v Trai FnKind::Method(trait_item.ident, sig, None, &trait_item.attrs), &sig.decl, body_id, - trait_item.span, trait_item.hir_id, ); } @@ -993,7 +962,7 @@ pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v Trai pub fn walk_trait_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, trait_item_ref: &'v TraitItemRef) { // N.B., deliberately force a compilation error if/when new fields are added. - let TraitItemRef { id, ident, ref kind, span: _, ref defaultness } = *trait_item_ref; + let TraitItemRef { id, ident, ref kind, ref defaultness } = *trait_item_ref; visitor.visit_nested_trait_item(id); visitor.visit_ident(ident); visitor.visit_associated_item_kind(kind); @@ -1029,7 +998,6 @@ pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplIt FnKind::Method(impl_item.ident, sig, Some(&impl_item.vis), &impl_item.attrs), &sig.decl, body_id, - impl_item.span, impl_item.hir_id, ); } @@ -1045,7 +1013,7 @@ pub fn walk_foreign_item_ref<'v, V: Visitor<'v>>( foreign_item_ref: &'v ForeignItemRef<'v>, ) { // N.B., deliberately force a compilation error if/when new fields are added. - let ForeignItemRef { id, ident, span: _, ref vis } = *foreign_item_ref; + let ForeignItemRef { id, ident, ref vis } = *foreign_item_ref; visitor.visit_nested_foreign_item(id); visitor.visit_ident(ident); visitor.visit_vis(vis); @@ -1053,7 +1021,7 @@ pub fn walk_foreign_item_ref<'v, V: Visitor<'v>>( pub fn walk_impl_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, impl_item_ref: &'v ImplItemRef<'v>) { // N.B., deliberately force a compilation error if/when new fields are added. - let ImplItemRef { id, ident, ref kind, span: _, ref vis, ref defaultness } = *impl_item_ref; + let ImplItemRef { id, ident, ref kind, ref vis, ref defaultness } = *impl_item_ref; visitor.visit_nested_impl_item(id); visitor.visit_ident(ident); visitor.visit_associated_item_kind(kind); @@ -1113,7 +1081,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>) visitor.visit_anon_const(count) } ExprKind::Struct(ref qpath, fields, ref optional_base) => { - visitor.visit_qpath(qpath, expression.hir_id, expression.span); + visitor.visit_qpath(qpath, expression.hir_id); for field in fields { visitor.visit_id(field.hir_id); visitor.visit_ident(field.ident); @@ -1129,7 +1097,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>) walk_list!(visitor, visit_expr, arguments); } ExprKind::MethodCall(ref segment, _, arguments, _) => { - visitor.visit_path_segment(expression.span, segment); + visitor.visit_path_segment(segment); walk_list!(visitor, visit_expr, arguments); } ExprKind::Binary(_, ref left_expression, ref right_expression) => { @@ -1159,7 +1127,6 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>) FnKind::Closure(&expression.attrs), function_declaration, body, - expression.span, expression.hir_id, ), ExprKind::Block(ref block, ref opt_label) => { @@ -1183,7 +1150,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>) visitor.visit_expr(index_expression) } ExprKind::Path(ref qpath) => { - visitor.visit_qpath(qpath, expression.hir_id, expression.span); + visitor.visit_qpath(qpath, expression.hir_id); } ExprKind::Break(ref destination, ref opt_expr) => { walk_list!(visitor, visit_label, &destination.label); diff --git a/compiler/rustc_hir/src/pat_util.rs b/compiler/rustc_hir/src/pat_util.rs index 9e0a6aae24272..edfe6a4113018 100644 --- a/compiler/rustc_hir/src/pat_util.rs +++ b/compiler/rustc_hir/src/pat_util.rs @@ -2,7 +2,6 @@ use crate::def::{CtorOf, DefKind, Res}; use crate::def_id::DefId; use crate::hir::{self, HirId, PatKind}; use rustc_span::symbol::Ident; -use rustc_span::Span; use std::iter::{Enumerate, ExactSizeIterator}; @@ -60,10 +59,10 @@ impl EnumerateAndAdjustIterator for T { impl hir::Pat<'_> { /// Call `f` on every "binding" in a pattern, e.g., on `a` in /// `match foo() { Some(a) => (), None => () }` - pub fn each_binding(&self, mut f: impl FnMut(hir::BindingAnnotation, HirId, Span, Ident)) { + pub fn each_binding(&self, mut f: impl FnMut(hir::BindingAnnotation, HirId, Ident)) { self.walk_always(|p| { if let PatKind::Binding(binding_mode, _, ident, _) = p.kind { - f(binding_mode, p.hir_id, p.span, ident); + f(binding_mode, p.hir_id, ident); } }); } @@ -72,17 +71,14 @@ impl hir::Pat<'_> { /// `match foo() { Some(a) => (), None => () }`. /// /// When encountering an or-pattern `p_0 | ... | p_n` only `p_0` will be visited. - pub fn each_binding_or_first( - &self, - f: &mut impl FnMut(hir::BindingAnnotation, HirId, Span, Ident), - ) { + pub fn each_binding_or_first(&self, f: &mut impl FnMut(hir::BindingAnnotation, HirId, Ident)) { self.walk(|p| match &p.kind { PatKind::Or(ps) => { ps[0].each_binding_or_first(f); false } PatKind::Binding(bm, _, ident, _) => { - f(*bm, p.hir_id, p.span, *ident); + f(*bm, p.hir_id, *ident); true } _ => true, @@ -150,7 +146,7 @@ impl hir::Pat<'_> { // ref bindings are be implicit after #42640 (default match binding modes). See issue #44848. pub fn contains_explicit_ref_binding(&self) -> Option { let mut result = None; - self.each_binding(|annotation, _, _, _| match annotation { + self.each_binding(|annotation, _, _| match annotation { hir::BindingAnnotation::Ref => match result { None | Some(hir::Mutability::Not) => result = Some(hir::Mutability::Not), _ => {} diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index ddd3827c81df6..09a6a44626f3e 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -7,7 +7,7 @@ use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent}; use rustc_ast_pretty::pp::{self, Breaks}; use rustc_ast_pretty::pprust::{Comments, PrintState}; use rustc_hir as hir; -use rustc_hir::{GenericArg, GenericParam, GenericParamKind, Node}; +use rustc_hir::{GenericArg, GenericParam, GenericParamKind, HirIdVec, Node}; use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier}; use rustc_span::source_map::{SourceMap, Spanned}; use rustc_span::symbol::{kw, Ident, IdentPrinter, Symbol}; @@ -83,6 +83,7 @@ pub struct State<'a> { pub s: pp::Printer, comments: Option>, ann: &'a (dyn PpAnn + 'a), + spans: &'a HirIdVec, } impl<'a> State<'a> { @@ -166,7 +167,7 @@ pub fn print_crate<'a>( input: String, ann: &'a dyn PpAnn, ) -> String { - let mut s = State::new_from_input(sm, filename, input, ann); + let mut s = State::new_from_input(sm, filename, input, ann, &krate.spans); // When printing the AST, we sometimes need to inject `#[no_std]` here. // Since you can't compile the HIR, it's not necessary. @@ -182,8 +183,18 @@ impl<'a> State<'a> { filename: FileName, input: String, ann: &'a dyn PpAnn, + spans: &'a HirIdVec, ) -> State<'a> { - State { s: pp::mk_printer(), comments: Some(Comments::new(sm, filename, input)), ann } + State { + s: pp::mk_printer(), + comments: Some(Comments::new(sm, filename, input)), + ann, + spans, + } + } + + fn span(&self, hir_id: hir::HirId) -> rustc_span::Span { + self.spans.get(hir_id).copied().unwrap_or(rustc_span::DUMMY_SP) } } @@ -191,7 +202,8 @@ pub fn to_string(ann: &dyn PpAnn, f: F) -> String where F: FnOnce(&mut State<'_>), { - let mut printer = State { s: pp::mk_printer(), comments: None, ann }; + let spans = &HirIdVec::default(); + let mut printer = State { s: pp::mk_printer(), comments: None, ann, spans }; f(&mut printer); printer.s.eof() } @@ -323,18 +335,21 @@ impl<'a> State<'a> { pub fn commasep_cmnt(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G) where F: FnMut(&mut State<'_>, &T), - G: FnMut(&T) -> rustc_span::Span, + G: FnMut(&State<'_>, &T) -> rustc_span::Span, { self.rbox(0, b); let len = elts.len(); let mut i = 0; for elt in elts { - self.maybe_print_comment(get_span(elt).hi()); + self.maybe_print_comment(get_span(self, elt).hi()); op(self, elt); i += 1; if i < len { self.s.word(","); - self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi())); + self.maybe_print_trailing_comment( + get_span(self, elt), + Some(get_span(self, &elts[i]).hi()), + ); self.space_if_not_bol(); } } @@ -342,7 +357,7 @@ impl<'a> State<'a> { } pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) { - self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span) + self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |_, e| e.span) } pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) { @@ -823,14 +838,15 @@ impl<'a> State<'a> { pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) { self.bopen(); for v in variants { + let span = self.span(v.id); self.space_if_not_bol(); - self.maybe_print_comment(v.span.lo()); + self.maybe_print_comment(span.lo()); self.print_outer_attributes(&v.attrs); self.ibox(INDENT_UNIT); self.print_variant(v); self.s.word(","); self.end(); - self.maybe_print_trailing_comment(v.span, None); + self.maybe_print_trailing_comment(span, None); } self.bclose(span) } @@ -878,7 +894,8 @@ impl<'a> State<'a> { if let hir::VariantData::Tuple(..) = struct_def { self.popen(); self.commasep(Inconsistent, struct_def.fields(), |s, field| { - s.maybe_print_comment(field.span.lo()); + let span = s.span(field.hir_id); + s.maybe_print_comment(span.lo()); s.print_outer_attributes(&field.attrs); s.print_visibility(&field.vis); s.print_type(&field.ty) @@ -899,8 +916,9 @@ impl<'a> State<'a> { self.hardbreak_if_not_bol(); for field in struct_def.fields() { + let span = self.span(field.hir_id); self.hardbreak_if_not_bol(); - self.maybe_print_comment(field.span.lo()); + self.maybe_print_comment(span.lo()); self.print_outer_attributes(&field.attrs); self.print_visibility(&field.vis); self.print_ident(field.ident); @@ -917,7 +935,7 @@ impl<'a> State<'a> { pub fn print_variant(&mut self, v: &hir::Variant<'_>) { self.head(""); let generics = hir::Generics::empty(); - self.print_struct(&v.data, &generics, v.ident.name, v.span, false); + self.print_struct(&v.data, &generics, v.ident.name, self.span(v.id), false); if let Some(ref d) = v.disr_expr { self.s.space(); self.word_space("="); @@ -1019,7 +1037,8 @@ impl<'a> State<'a> { } pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) { - self.maybe_print_comment(st.span.lo()); + let span = self.span(st.hir_id); + self.maybe_print_comment(span.lo()); match st.kind { hir::StmtKind::Local(ref loc) => { self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc)); @@ -1038,7 +1057,7 @@ impl<'a> State<'a> { if stmt_ends_with_semi(&st.kind) { self.s.word(";"); } - self.maybe_print_trailing_comment(st.span, None) + self.maybe_print_trailing_comment(span, None) } pub fn print_block(&mut self, blk: &hir::Block<'_>) { @@ -1065,7 +1084,8 @@ impl<'a> State<'a> { hir::BlockCheckMode::PopUnsafeBlock(..) => self.word_space("pop_unsafe"), hir::BlockCheckMode::DefaultBlock => (), } - self.maybe_print_comment(blk.span.lo()); + let span = self.span(blk.hir_id); + self.maybe_print_comment(span.lo()); self.ann.pre(self, AnnNode::Block(blk)); self.bopen(); @@ -1077,9 +1097,9 @@ impl<'a> State<'a> { if let Some(ref expr) = blk.expr { self.space_if_not_bol(); self.print_expr(&expr); - self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi())); + self.maybe_print_trailing_comment(expr.span, Some(span.hi())); } - self.bclose_maybe_open(blk.span, close_box); + self.bclose_maybe_open(span, close_box); self.ann.post(self, AnnNode::Block(blk)) } @@ -1169,7 +1189,7 @@ impl<'a> State<'a> { s.print_expr(&field.expr); s.end() }, - |f| f.span, + |s, f| s.span(f.hir_id), ); match *wth { Some(ref expr) => { @@ -1819,7 +1839,8 @@ impl<'a> State<'a> { } pub fn print_pat(&mut self, pat: &hir::Pat<'_>) { - self.maybe_print_comment(pat.span.lo()); + let span = self.span(pat.hir_id); + self.maybe_print_comment(span.lo()); self.ann.pre(self, AnnNode::Pat(pat)); // Pat isn't normalized, but the beauty of it // is that it doesn't matter @@ -1883,7 +1904,7 @@ impl<'a> State<'a> { s.print_pat(&f.pat); s.end() }, - |f| f.pat.span, + |s, f| s.span(f.pat.hir_id), ); if etc { if !fields.is_empty() { diff --git a/compiler/rustc_index/src/vec.rs b/compiler/rustc_index/src/vec.rs index 2420f82c0418d..db0f7f86a97f2 100644 --- a/compiler/rustc_index/src/vec.rs +++ b/compiler/rustc_index/src/vec.rs @@ -694,9 +694,7 @@ impl IndexVec { pub fn convert_index_type(self) -> IndexVec { IndexVec { raw: self.raw, _marker: PhantomData } } -} -impl IndexVec { /// Grows the index vector so that it contains an entry for /// `elem`; if that is already true, then has no /// effect. Otherwise, inserts new values as needed by invoking @@ -709,11 +707,6 @@ impl IndexVec { } } - #[inline] - pub fn resize(&mut self, new_len: usize, value: T) { - self.raw.resize(new_len, value) - } - #[inline] pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) { let min_new_len = elem.index() + 1; @@ -721,6 +714,13 @@ impl IndexVec { } } +impl IndexVec { + #[inline] + pub fn resize(&mut self, new_len: usize, value: T) { + self.raw.resize(new_len, value) + } +} + impl IndexVec { #[inline] pub fn binary_search(&self, value: &T) -> Result { diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index d1d6cb43fc74c..a0dac3ce1ffcc 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -162,7 +162,7 @@ fn msg_span_from_early_bound_and_free_regions( if let Some(param) = tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(br.name)) { - sp = param.span; + sp = tcx.hir().span(param.hir_id); } (format!("the lifetime `{}` as defined on", br.name), sp) } @@ -173,7 +173,7 @@ fn msg_span_from_early_bound_and_free_regions( if let Some(param) = tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(name)) { - sp = param.span; + sp = tcx.hir().span(param.hir_id); } (format!("the lifetime `{}` as defined on", name), sp) } diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index e097264ec8aa0..62846b097df84 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs @@ -370,7 +370,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { local_visitor.visit_expr(expr); } let err_span = if let Some(pattern) = local_visitor.found_arg_pattern { - pattern.span + self.tcx.hir().span(pattern.hir_id) } else if let Some(span) = arg_data.span { // `span` here lets us point at `sum` instead of the entire right hand side expr: // error[E0282]: type annotations needed @@ -537,12 +537,13 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { // with the type parameter `_` specified // ``` err.span_label( - pattern.span, + self.tcx.hir().span(pattern.hir_id), format!("consider giving this closure parameter {}", suffix), ); } else if let Some(pattern) = local_visitor.found_local_pattern { + let pattern_span = self.tcx.hir().span(pattern.hir_id); let msg = if let Some(simple_ident) = pattern.simple_ident() { - match pattern.span.desugaring_kind() { + match pattern_span.desugaring_kind() { None => format!("consider giving `{}` {}", simple_ident, suffix), Some(DesugaringKind::ForLoop(_)) => { "the element type for this iterator is not specified".to_string() @@ -552,7 +553,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { } else { format!("consider giving this pattern {}", suffix) }; - err.span_label(pattern.span, msg); + err.span_label(pattern_span, msg); } else if let Some(e) = local_visitor.found_method_call { if let ExprKind::MethodCall(segment, ..) = &e.kind { // Suggest specifying type params or point out the return type of the call: diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 374bd6d0d791f..41e3a27859280 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -177,7 +177,8 @@ impl<'tcx> LateLintPass<'tcx> for BoxPointers { hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { for struct_field in struct_def.fields() { let def_id = cx.tcx.hir().local_def_id(struct_field.hir_id); - self.check_heap_type(cx, struct_field.span, cx.tcx.type_of(def_id)); + let span = cx.tcx.hir().span(struct_field.hir_id); + self.check_heap_type(cx, span, cx.tcx.type_of(def_id)); } } _ => (), @@ -241,7 +242,8 @@ impl<'tcx> LateLintPass<'tcx> for NonShorthandFieldPatterns { if fieldpat.is_shorthand { continue; } - if fieldpat.span.from_expansion() { + let fieldpat_span = cx.tcx.hir().span(fieldpat.hir_id); + if fieldpat_span.from_expansion() { // Don't lint if this is a macro expansion: macro authors // shouldn't have to worry about this kind of style issue // (Issue #49588) @@ -251,7 +253,7 @@ impl<'tcx> LateLintPass<'tcx> for NonShorthandFieldPatterns { if cx.tcx.find_field_index(ident, &variant) == Some(cx.tcx.field_index(fieldpat.hir_id, cx.typeck_results())) { - cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span, |lint| { + cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat_span, |lint| { let mut err = lint .build(&format!("the `{}:` in this pattern is redundant", ident)); let binding = match binding_annot { @@ -266,7 +268,7 @@ impl<'tcx> LateLintPass<'tcx> for NonShorthandFieldPatterns { ident.to_string() }; err.span_suggestion( - fieldpat.span, + fieldpat_span, "use shorthand field pattern", ident, Applicability::MachineApplicable, @@ -515,14 +517,22 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { } fn check_crate(&mut self, cx: &LateContext<'_>, krate: &hir::Crate<'_>) { - self.check_missing_docs_attrs(cx, None, &krate.item.attrs, krate.item.span, "the", "crate"); + self.check_missing_docs_attrs( + cx, + None, + &krate.item.attrs, + cx.tcx.hir().span(hir::CRATE_HIR_ID), + "the", + "crate", + ); for macro_def in krate.exported_macros { let has_doc = macro_def.attrs.iter().any(|a| has_doc(cx.sess(), a)); if !has_doc { + let span = cx.tcx.hir().span(macro_def.hir_id); cx.struct_span_lint( MISSING_DOCS, - cx.tcx.sess.source_map().guess_head_span(macro_def.span), + cx.tcx.sess.source_map().guess_head_span(span), |lint| lint.build("missing documentation for macro").emit(), ); } @@ -627,19 +637,14 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { fn check_struct_field(&mut self, cx: &LateContext<'_>, sf: &hir::StructField<'_>) { if !sf.is_positional() { - self.check_missing_docs_attrs( - cx, - Some(sf.hir_id), - &sf.attrs, - sf.span, - "a", - "struct field", - ) + let span = cx.tcx.hir().span(sf.hir_id); + self.check_missing_docs_attrs(cx, Some(sf.hir_id), &sf.attrs, span, "a", "struct field") } } fn check_variant(&mut self, cx: &LateContext<'_>, v: &hir::Variant<'_>) { - self.check_missing_docs_attrs(cx, Some(v.id), &v.attrs, v.span, "a", "variant"); + let span = cx.tcx.hir().span(v.id); + self.check_missing_docs_attrs(cx, Some(v.id), &v.attrs, span, "a", "variant"); } } @@ -1326,7 +1331,8 @@ impl<'tcx> LateLintPass<'tcx> for UnreachablePub { } fn check_struct_field(&mut self, cx: &LateContext<'_>, field: &hir::StructField<'_>) { - self.perform_lint(cx, "field", field.hir_id, &field.vis, field.span, false); + let span = cx.tcx.hir().span(field.hir_id); + self.perform_lint(cx, "field", field.hir_id, &field.vis, span, false); } fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) { @@ -1378,36 +1384,42 @@ impl TypeAliasBounds { } } - fn suggest_changing_assoc_types(ty: &hir::Ty<'_>, err: &mut DiagnosticBuilder<'_>) { + fn suggest_changing_assoc_types( + tcx: TyCtxt<'_>, + ty: &hir::Ty<'_>, + err: &mut DiagnosticBuilder<'_>, + ) { // Access to associates types should use `::Assoc`, which does not need a // bound. Let's see if this type does that. // We use a HIR visitor to walk the type. use rustc_hir::intravisit::{self, Visitor}; - struct WalkAssocTypes<'a, 'db> { + struct WalkAssocTypes<'a, 'db, 'tcx> { err: &'a mut DiagnosticBuilder<'db>, + tcx: TyCtxt<'tcx>, } - impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> { + impl<'a, 'db, 'tcx, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db, 'tcx> { type Map = intravisit::ErasedMap<'v>; fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap { intravisit::NestedVisitorMap::None } - fn visit_qpath(&mut self, qpath: &'v hir::QPath<'v>, id: hir::HirId, span: Span) { + fn visit_qpath(&mut self, qpath: &'v hir::QPath<'v>, id: hir::HirId) { if TypeAliasBounds::is_type_variable_assoc(qpath) { + let span = self.tcx.hir().span(id); self.err.span_help( span, "use fully disambiguated paths (i.e., `::Assoc`) to refer to \ associated types in type aliases", ); } - intravisit::walk_qpath(self, qpath, id, span) + intravisit::walk_qpath(self, qpath, id) } } // Let's go for a walk! - let mut visitor = WalkAssocTypes { err }; + let mut visitor = WalkAssocTypes { err, tcx }; visitor.visit_ty(ty); } } @@ -1443,7 +1455,7 @@ impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds { Applicability::MachineApplicable, ); if !suggested_changing_assoc_types { - TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err); + TypeAliasBounds::suggest_changing_assoc_types(cx.tcx, ty, &mut err); suggested_changing_assoc_types = true; } err.emit(); @@ -1456,7 +1468,8 @@ impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds { let suggestion = spans .iter() .map(|sp| { - let start = param.span.between(*sp); // Include the `:` in `T: Bound`. + let param_span = cx.tcx.hir().span(param.hir_id); + let start = param_span.between(*sp); // Include the `:` in `T: Bound`. (start.to(*sp), String::new()) }) .collect(); @@ -1468,7 +1481,7 @@ impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds { and should be removed"; err.multipart_suggestion(&msg, suggestion, Applicability::MachineApplicable); if !suggested_changing_assoc_types { - TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err); + TypeAliasBounds::suggest_changing_assoc_types(cx.tcx, ty, &mut err); suggested_changing_assoc_types = true; } err.emit(); @@ -2111,8 +2124,9 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements { infer_static, ); bound_count += bound_spans.len(); + let param_span = cx.tcx.hir().span(param.hir_id); lint_spans.extend(self.consolidate_outlives_bound_spans( - param.span.shrink_to_hi(), + param_span.shrink_to_hi(), ¶m.bounds, bound_spans, )); diff --git a/compiler/rustc_lint/src/late.rs b/compiler/rustc_lint/src/late.rs index 015e109871182..154386d05604c 100644 --- a/compiler/rustc_lint/src/late.rs +++ b/compiler/rustc_lint/src/late.rs @@ -26,7 +26,6 @@ use rustc_middle::hir::map::Map; use rustc_middle::ty::{self, TyCtxt}; use rustc_session::lint::LintPass; use rustc_span::symbol::Symbol; -use rustc_span::Span; use std::any::Any; use std::cell::Cell; @@ -76,10 +75,10 @@ impl<'tcx, T: LateLintPass<'tcx>> LateContextAndPass<'tcx, T> { self.context.param_env = old_param_env; } - fn process_mod(&mut self, m: &'tcx hir::Mod<'tcx>, s: Span, n: hir::HirId) { - lint_callback!(self, check_mod, m, s, n); + fn process_mod(&mut self, m: &'tcx hir::Mod<'tcx>, n: hir::HirId) { + lint_callback!(self, check_mod, m, n); hir_visit::walk_mod(self, m, n); - lint_callback!(self, check_mod_post, m, s, n); + lint_callback!(self, check_mod_post, m, n); } fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) { @@ -189,7 +188,6 @@ impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPas fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl<'tcx>, body_id: hir::BodyId, - span: Span, id: hir::HirId, ) { // Wrap in typeck results here, not just in visit_nested_body, @@ -197,9 +195,9 @@ impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPas let old_enclosing_body = self.context.enclosing_body.replace(body_id); let old_cached_typeck_results = self.context.cached_typeck_results.take(); let body = self.context.tcx.hir().body(body_id); - lint_callback!(self, check_fn, fk, decl, body, span, id); - hir_visit::walk_fn(self, fk, decl, body_id, span, id); - lint_callback!(self, check_fn_post, fk, decl, body, span, id); + lint_callback!(self, check_fn, fk, decl, body, id); + hir_visit::walk_fn(self, fk, decl, body_id, id); + lint_callback!(self, check_fn_post, fk, decl, body, id); self.context.enclosing_body = old_enclosing_body; self.context.cached_typeck_results.set(old_cached_typeck_results); } @@ -210,7 +208,6 @@ impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPas _: Symbol, _: &'tcx hir::Generics<'tcx>, _: hir::HirId, - _: Span, ) { lint_callback!(self, check_struct_def, s); hir_visit::walk_struct_def(self, s); @@ -242,13 +239,9 @@ impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPas hir_visit::walk_ty(self, t); } - fn visit_name(&mut self, sp: Span, name: Symbol) { - lint_callback!(self, check_name, sp, name); - } - - fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, s: Span, n: hir::HirId) { + fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, n: hir::HirId) { if !self.context.only_module { - self.process_mod(m, s, n); + self.process_mod(m, n); } } @@ -387,8 +380,8 @@ fn late_lint_mod_pass<'tcx, T: LateLintPass<'tcx>>( let mut cx = LateContextAndPass { context, pass }; - let (module, span, hir_id) = tcx.hir().get_module(module_def_id); - cx.process_mod(module, span, hir_id); + let (module, hir_id) = tcx.hir().get_module(module_def_id); + cx.process_mod(module, hir_id); // Visit the crate attributes if hir_id == hir::CRATE_HIR_ID { diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 2336b52619ab8..de3bae81215e4 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -72,7 +72,7 @@ use rustc_session::lint::builtin::{ EXPLICIT_OUTLIVES_REQUIREMENTS, INVALID_CODEBLOCK_ATTRIBUTES, INVALID_HTML_TAGS, MISSING_DOC_CODE_EXAMPLES, NON_AUTOLINKS, PRIVATE_DOC_TESTS, }; -use rustc_span::symbol::{Ident, Symbol}; +use rustc_span::symbol::Ident; use rustc_span::Span; use array_into_iter::ArrayIntoIter; diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index ebd6190dc74cc..06e7e006f8e3d 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -8,7 +8,7 @@ use rustc_hir::intravisit::FnKind; use rustc_hir::{GenericParamKind, PatKind}; use rustc_middle::ty; use rustc_span::symbol::sym; -use rustc_span::{symbol::Ident, BytePos, Span}; +use rustc_span::{symbol::Ident, BytePos}; use rustc_target::spec::abi::Abi; #[derive(PartialEq)] @@ -308,13 +308,7 @@ impl NonSnakeCase { } impl<'tcx> LateLintPass<'tcx> for NonSnakeCase { - fn check_mod( - &mut self, - cx: &LateContext<'_>, - _: &'tcx hir::Mod<'tcx>, - _: Span, - id: hir::HirId, - ) { + fn check_mod(&mut self, cx: &LateContext<'_>, _: &'tcx hir::Mod<'tcx>, id: hir::HirId) { if id != hir::CRATE_HIR_ID { return; } @@ -372,7 +366,6 @@ impl<'tcx> LateLintPass<'tcx> for NonSnakeCase { fk: FnKind<'_>, _: &hir::FnDecl<'_>, _: &hir::Body<'_>, - _: Span, id: hir::HirId, ) { match &fk { diff --git a/compiler/rustc_lint/src/passes.rs b/compiler/rustc_lint/src/passes.rs index 828f283d2a95a..db7c8271edf0b 100644 --- a/compiler/rustc_lint/src/passes.rs +++ b/compiler/rustc_lint/src/passes.rs @@ -5,7 +5,7 @@ use rustc_data_structures::sync; use rustc_hir as hir; use rustc_session::lint::builtin::HardwiredLints; use rustc_session::lint::LintPass; -use rustc_span::symbol::{Ident, Symbol}; +use rustc_span::symbol::Ident; use rustc_span::Span; #[macro_export] @@ -15,11 +15,10 @@ macro_rules! late_lint_methods { fn check_param(a: &$hir hir::Param<$hir>); fn check_body(a: &$hir hir::Body<$hir>); fn check_body_post(a: &$hir hir::Body<$hir>); - fn check_name(a: Span, b: Symbol); fn check_crate(a: &$hir hir::Crate<$hir>); fn check_crate_post(a: &$hir hir::Crate<$hir>); - fn check_mod(a: &$hir hir::Mod<$hir>, b: Span, c: hir::HirId); - fn check_mod_post(a: &$hir hir::Mod<$hir>, b: Span, c: hir::HirId); + fn check_mod(a: &$hir hir::Mod<$hir>, c: hir::HirId); + fn check_mod_post(a: &$hir hir::Mod<$hir>, c: hir::HirId); fn check_foreign_item(a: &$hir hir::ForeignItem<$hir>); fn check_foreign_item_post(a: &$hir hir::ForeignItem<$hir>); fn check_item(a: &$hir hir::Item<$hir>); @@ -42,13 +41,11 @@ macro_rules! late_lint_methods { a: rustc_hir::intravisit::FnKind<$hir>, b: &$hir hir::FnDecl<$hir>, c: &$hir hir::Body<$hir>, - d: Span, e: hir::HirId); fn check_fn_post( a: rustc_hir::intravisit::FnKind<$hir>, b: &$hir hir::FnDecl<$hir>, c: &$hir hir::Body<$hir>, - d: Span, e: hir::HirId ); fn check_trait_item(a: &$hir hir::TraitItem<$hir>); diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 9ad9d53cd0db3..0ebc3d8c02e61 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -140,7 +140,9 @@ fn lint_overflowing_range_endpoint<'tcx>( if eps[1].expr.hir_id == expr.hir_id && lit_val - 1 == max { cx.struct_span_lint(OVERFLOWING_LITERALS, parent_expr.span, |lint| { let mut err = lint.build(&format!("range endpoint is out of range for `{}`", ty)); - if let Ok(start) = cx.sess().source_map().span_to_snippet(eps[0].span) { + if let Ok(start) = + cx.sess().source_map().span_to_snippet(cx.tcx.hir().span(eps[0].hir_id)) + { use ast::{LitIntType, LitKind}; // We need to preserve the literal's suffix, // as it may determine typing information. @@ -1266,7 +1268,6 @@ impl<'tcx> LateLintPass<'tcx> for ImproperCTypesDefinitions { kind: hir::intravisit::FnKind<'tcx>, decl: &'tcx hir::FnDecl<'_>, _: &'tcx hir::Body<'_>, - _: Span, hir_id: hir::HirId, ) { use hir::intravisit::FnKind; @@ -1342,18 +1343,15 @@ impl<'tcx> LateLintPass<'tcx> for VariantSizeDifferences { // We only warn if the largest variant is at least thrice as large as // the second-largest. if largest > slargest * 3 && slargest > 0 { - cx.struct_span_lint( - VARIANT_SIZE_DIFFERENCES, - enum_definition.variants[largest_index].span, - |lint| { - lint.build(&format!( - "enum variant is more than three times \ + let span = cx.tcx.hir().span(enum_definition.variants[largest_index].id); + cx.struct_span_lint(VARIANT_SIZE_DIFFERENCES, span, |lint| { + lint.build(&format!( + "enum variant is more than three times \ larger ({} bytes) than the next largest", - largest - )) - .emit() - }, - ); + largest + )) + .emit() + }); } } } diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 35915dc7a9753..2e5c78a6cb771 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -101,8 +101,9 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { return; } + let span = cx.tcx.hir().span(s.hir_id); let ty = cx.typeck_results().expr_ty(&expr); - let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1); + let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, span, "", "", 1); let mut fn_warned = false; let mut op_warned = false; @@ -124,7 +125,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { _ => None, }; if let Some(def_id) = maybe_def_id { - fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", ""); + fn_warned = check_must_use_def(cx, def_id, span, "return value of ", ""); } else if type_permits_lack_of_use { // We don't warn about unused unit or uninhabited types. // (See https://github.com/rust-lang/rust/issues/43806 for details.) @@ -166,7 +167,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { } if !(type_permits_lack_of_use || fn_warned || op_warned) { - cx.struct_span_lint(UNUSED_RESULTS, s.span, |lint| lint.build("unused result").emit()); + cx.struct_span_lint(UNUSED_RESULTS, span, |lint| lint.build("unused result").emit()); } // Returns whether an error has been emitted (and thus another does not need to be later). @@ -349,19 +350,20 @@ impl<'tcx> LateLintPass<'tcx> for PathStatements { fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) { if let hir::StmtKind::Semi(expr) = s.kind { if let hir::ExprKind::Path(_) = expr.kind { - cx.struct_span_lint(PATH_STATEMENTS, s.span, |lint| { + let span = cx.tcx.hir().span(s.hir_id); + cx.struct_span_lint(PATH_STATEMENTS, span, |lint| { let ty = cx.typeck_results().expr_ty(expr); if ty.needs_drop(cx.tcx, cx.param_env) { let mut lint = lint.build("path statement drops value"); if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) { lint.span_suggestion( - s.span, + span, "use `drop` to clarify the intent", format!("drop({});", snippet), Applicability::MachineApplicable, ); } else { - lint.span_help(s.span, "use `drop` to clarify the intent"); + lint.span_help(span, "use `drop` to clarify the intent"); } lint.emit() } else { diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index f6ae8275a8f32..15a4969dedc15 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1427,9 +1427,10 @@ impl EncodeContext<'a, 'tcx> { /// Serialize the text of exported macros fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) { let def_id = self.tcx.hir().local_def_id(macro_def.hir_id).to_def_id(); + let span = self.tcx.hir().span(macro_def.hir_id); record!(self.tables.kind[def_id] <- EntryKind::MacroDef(self.lazy(macro_def.ast.clone()))); record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id)); - record!(self.tables.span[def_id] <- macro_def.span); + record!(self.tables.span[def_id] <- span); record!(self.tables.attributes[def_id] <- macro_def.attrs); self.encode_ident_span(def_id, macro_def.ident); self.encode_stability(def_id); diff --git a/compiler/rustc_middle/src/hir/map/blocks.rs b/compiler/rustc_middle/src/hir/map/blocks.rs index 9d392c7b26bf7..14e6528c30656 100644 --- a/compiler/rustc_middle/src/hir/map/blocks.rs +++ b/compiler/rustc_middle/src/hir/map/blocks.rs @@ -17,7 +17,6 @@ use rustc_hir as hir; use rustc_hir::intravisit::FnKind; use rustc_hir::{Expr, FnDecl, Node}; use rustc_span::symbol::Ident; -use rustc_span::Span; /// An FnLikeNode is a Node that is like a fn, in that it has a decl /// and a body (as well as a NodeId, a span, etc). @@ -104,7 +103,6 @@ struct ItemFnParts<'a> { generics: &'a hir::Generics<'a>, body: hir::BodyId, id: hir::HirId, - span: Span, attrs: &'a [Attribute], } @@ -114,19 +112,12 @@ struct ClosureParts<'a> { decl: &'a FnDecl<'a>, body: hir::BodyId, id: hir::HirId, - span: Span, attrs: &'a [Attribute], } impl<'a> ClosureParts<'a> { - fn new( - d: &'a FnDecl<'a>, - b: hir::BodyId, - id: hir::HirId, - s: Span, - attrs: &'a [Attribute], - ) -> Self { - ClosureParts { decl: d, body: b, id, span: s, attrs } + fn new(d: &'a FnDecl<'a>, b: hir::BodyId, id: hir::HirId, attrs: &'a [Attribute]) -> Self { + ClosureParts { decl: d, body: b, id, attrs } } } @@ -146,7 +137,7 @@ impl<'a> FnLikeNode<'a> { pub fn body(self) -> hir::BodyId { self.handle( |i: ItemFnParts<'a>| i.body, - |_, _, _: &'a hir::FnSig<'a>, _, body: hir::BodyId, _, _| body, + |_, _, _: &'a hir::FnSig<'a>, _, body: hir::BodyId, _| body, |c: ClosureParts<'a>| c.body, ) } @@ -154,23 +145,15 @@ impl<'a> FnLikeNode<'a> { pub fn decl(self) -> &'a FnDecl<'a> { self.handle( |i: ItemFnParts<'a>| &*i.decl, - |_, _, sig: &'a hir::FnSig<'a>, _, _, _, _| &sig.decl, + |_, _, sig: &'a hir::FnSig<'a>, _, _, _| &sig.decl, |c: ClosureParts<'a>| c.decl, ) } - pub fn span(self) -> Span { - self.handle( - |i: ItemFnParts<'_>| i.span, - |_, _, _: &'a hir::FnSig<'a>, _, _, span, _| span, - |c: ClosureParts<'_>| c.span, - ) - } - pub fn id(self) -> hir::HirId { self.handle( |i: ItemFnParts<'_>| i.id, - |id, _, _: &'a hir::FnSig<'a>, _, _, _, _| id, + |id, _, _: &'a hir::FnSig<'a>, _, _, _| id, |c: ClosureParts<'_>| c.id, ) } @@ -192,7 +175,7 @@ impl<'a> FnLikeNode<'a> { FnKind::ItemFn(p.ident, p.generics, p.header, p.vis, p.attrs) }; let closure = |c: ClosureParts<'a>| FnKind::Closure(c.attrs); - let method = |_, ident: Ident, sig: &'a hir::FnSig<'a>, vis, _, _, attrs| { + let method = |_, ident: Ident, sig: &'a hir::FnSig<'a>, vis, _, attrs| { FnKind::Method(ident, sig, vis, attrs) }; self.handle(item, method, closure) @@ -207,7 +190,6 @@ impl<'a> FnLikeNode<'a> { &'a hir::FnSig<'a>, Option<&'a hir::Visibility<'a>>, hir::BodyId, - Span, &'a [Attribute], ) -> A, C: FnOnce(ClosureParts<'a>) -> A, @@ -220,7 +202,6 @@ impl<'a> FnLikeNode<'a> { decl: &sig.decl, body: block, vis: &i.vis, - span: i.span, attrs: &i.attrs, header: sig.header, generics, @@ -229,19 +210,19 @@ impl<'a> FnLikeNode<'a> { }, Node::TraitItem(ti) => match ti.kind { hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => { - method(ti.hir_id, ti.ident, sig, None, body, ti.span, &ti.attrs) + method(ti.hir_id, ti.ident, sig, None, body, &ti.attrs) } _ => bug!("trait method FnLikeNode that is not fn-like"), }, Node::ImplItem(ii) => match ii.kind { hir::ImplItemKind::Fn(ref sig, body) => { - method(ii.hir_id, ii.ident, sig, Some(&ii.vis), body, ii.span, &ii.attrs) + method(ii.hir_id, ii.ident, sig, Some(&ii.vis), body, &ii.attrs) } _ => bug!("impl method FnLikeNode that is not fn-like"), }, Node::Expr(e) => match e.kind { hir::ExprKind::Closure(_, ref decl, block, _fn_decl_span, _gen) => { - closure(ClosureParts::new(&decl, block, e.hir_id, e.span, &e.attrs)) + closure(ClosureParts::new(&decl, block, e.hir_id, &e.attrs)) } _ => bug!("expr FnLikeNode that is not fn-like"), }, diff --git a/compiler/rustc_middle/src/hir/map/collector.rs b/compiler/rustc_middle/src/hir/map/collector.rs index 872fcb0f581d0..881f005dc6487 100644 --- a/compiler/rustc_middle/src/hir/map/collector.rs +++ b/compiler/rustc_middle/src/hir/map/collector.rs @@ -16,7 +16,7 @@ use rustc_hir::*; use rustc_index::vec::{Idx, IndexVec}; use rustc_session::{CrateDisambiguator, Session}; use rustc_span::source_map::SourceMap; -use rustc_span::{Span, Symbol, DUMMY_SP}; +use rustc_span::Symbol; use std::iter::repeat; @@ -119,6 +119,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { modules: _, proc_macros: _, trait_map: _, + spans: _, } = *krate; hash_body(&mut hcx, root_mod_def_path_hash, item, &mut hir_body_nodes) @@ -233,11 +234,11 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { } } - fn insert(&mut self, span: Span, hir_id: HirId, node: Node<'hir>) { - self.insert_with_hash(span, hir_id, node, Fingerprint::ZERO) + fn insert(&mut self, hir_id: HirId, node: Node<'hir>) { + self.insert_with_hash(hir_id, node, Fingerprint::ZERO) } - fn insert_with_hash(&mut self, span: Span, hir_id: HirId, node: Node<'hir>, hash: Fingerprint) { + fn insert_with_hash(&mut self, hir_id: HirId, node: Node<'hir>, hash: Fingerprint) { let entry = Entry { parent: self.parent_node, node }; // Make sure that the DepNode of some node coincides with the HirId @@ -249,6 +250,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { None => format!("{:?}", node), }; + let span = self.krate.spans[hir_id]; span_bug!( span, "inconsistent DepNode at `{:?}` for `{}`: \ @@ -330,7 +332,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { fn visit_param(&mut self, param: &'hir Param<'hir>) { let node = Node::Param(param); - self.insert(param.pat.span, param.hir_id, node); + self.insert(param.hir_id, node); self.with_parent(param.hir_id, |this| { intravisit::walk_param(this, param); }); @@ -343,12 +345,13 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { self.definitions.opt_hir_id_to_local_def_id(i.hir_id).unwrap() ); self.with_dep_node_owner(i.hir_id.owner, i, |this, hash| { - this.insert_with_hash(i.span, i.hir_id, Node::Item(i), hash); + this.insert_with_hash(i.hir_id, Node::Item(i), hash); + this.with_parent(i.hir_id, |this| { if let ItemKind::Struct(ref struct_def, _) = i.kind { // If this is a tuple or unit-like struct, register the constructor. if let Some(ctor_hir_id) = struct_def.ctor_hir_id() { - this.insert(i.span, ctor_hir_id, Node::Ctor(struct_def)); + this.insert(ctor_hir_id, Node::Ctor(struct_def)); } } intravisit::walk_item(this, i); @@ -362,7 +365,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { self.definitions.opt_hir_id_to_local_def_id(fi.hir_id).unwrap() ); self.with_dep_node_owner(fi.hir_id.owner, fi, |this, hash| { - this.insert_with_hash(fi.span, fi.hir_id, Node::ForeignItem(fi), hash); + this.insert_with_hash(fi.hir_id, Node::ForeignItem(fi), hash); this.with_parent(fi.hir_id, |this| { intravisit::walk_foreign_item(this, fi); @@ -381,14 +384,14 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { self.definitions.opt_hir_id_to_local_def_id(param.hir_id).unwrap() ); self.with_dep_node_owner(param.hir_id.owner, param, |this, hash| { - this.insert_with_hash(param.span, param.hir_id, Node::GenericParam(param), hash); + this.insert_with_hash(param.hir_id, Node::GenericParam(param), hash); this.with_parent(param.hir_id, |this| { intravisit::walk_generic_param(this, param); }); }); } else { - self.insert(param.span, param.hir_id, Node::GenericParam(param)); + self.insert(param.hir_id, Node::GenericParam(param)); intravisit::walk_generic_param(self, param); } } @@ -399,7 +402,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { self.definitions.opt_hir_id_to_local_def_id(ti.hir_id).unwrap() ); self.with_dep_node_owner(ti.hir_id.owner, ti, |this, hash| { - this.insert_with_hash(ti.span, ti.hir_id, Node::TraitItem(ti), hash); + this.insert_with_hash(ti.hir_id, Node::TraitItem(ti), hash); this.with_parent(ti.hir_id, |this| { intravisit::walk_trait_item(this, ti); @@ -413,7 +416,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { self.definitions.opt_hir_id_to_local_def_id(ii.hir_id).unwrap() ); self.with_dep_node_owner(ii.hir_id.owner, ii, |this, hash| { - this.insert_with_hash(ii.span, ii.hir_id, Node::ImplItem(ii), hash); + this.insert_with_hash(ii.hir_id, Node::ImplItem(ii), hash); this.with_parent(ii.hir_id, |this| { intravisit::walk_impl_item(this, ii); @@ -424,7 +427,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { fn visit_pat(&mut self, pat: &'hir Pat<'hir>) { let node = if let PatKind::Binding(..) = pat.kind { Node::Binding(pat) } else { Node::Pat(pat) }; - self.insert(pat.span, pat.hir_id, node); + self.insert(pat.hir_id, node); self.with_parent(pat.hir_id, |this| { intravisit::walk_pat(this, pat); @@ -434,7 +437,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { fn visit_arm(&mut self, arm: &'hir Arm<'hir>) { let node = Node::Arm(arm); - self.insert(arm.span, arm.hir_id, node); + self.insert(arm.hir_id, node); self.with_parent(arm.hir_id, |this| { intravisit::walk_arm(this, arm); @@ -442,7 +445,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { } fn visit_anon_const(&mut self, constant: &'hir AnonConst) { - self.insert(DUMMY_SP, constant.hir_id, Node::AnonConst(constant)); + self.insert(constant.hir_id, Node::AnonConst(constant)); self.with_parent(constant.hir_id, |this| { intravisit::walk_anon_const(this, constant); @@ -450,7 +453,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { } fn visit_expr(&mut self, expr: &'hir Expr<'hir>) { - self.insert(expr.span, expr.hir_id, Node::Expr(expr)); + self.insert(expr.hir_id, Node::Expr(expr)); self.with_parent(expr.hir_id, |this| { intravisit::walk_expr(this, expr); @@ -458,22 +461,22 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { } fn visit_stmt(&mut self, stmt: &'hir Stmt<'hir>) { - self.insert(stmt.span, stmt.hir_id, Node::Stmt(stmt)); + self.insert(stmt.hir_id, Node::Stmt(stmt)); self.with_parent(stmt.hir_id, |this| { intravisit::walk_stmt(this, stmt); }); } - fn visit_path_segment(&mut self, path_span: Span, path_segment: &'hir PathSegment<'hir>) { + fn visit_path_segment(&mut self, path_segment: &'hir PathSegment<'hir>) { if let Some(hir_id) = path_segment.hir_id { - self.insert(path_span, hir_id, Node::PathSegment(path_segment)); + self.insert(hir_id, Node::PathSegment(path_segment)); } - intravisit::walk_path_segment(self, path_span, path_segment); + intravisit::walk_path_segment(self, path_segment); } fn visit_ty(&mut self, ty: &'hir Ty<'hir>) { - self.insert(ty.span, ty.hir_id, Node::Ty(ty)); + self.insert(ty.hir_id, Node::Ty(ty)); self.with_parent(ty.hir_id, |this| { intravisit::walk_ty(this, ty); @@ -481,7 +484,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { } fn visit_trait_ref(&mut self, tr: &'hir TraitRef<'hir>) { - self.insert(tr.path.span, tr.hir_ref_id, Node::TraitRef(tr)); + self.insert(tr.hir_ref_id, Node::TraitRef(tr)); self.with_parent(tr.hir_ref_id, |this| { intravisit::walk_trait_ref(this, tr); @@ -493,34 +496,33 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { fk: intravisit::FnKind<'hir>, fd: &'hir FnDecl<'hir>, b: BodyId, - s: Span, id: HirId, ) { assert_eq!(self.parent_node, id); - intravisit::walk_fn(self, fk, fd, b, s, id); + intravisit::walk_fn(self, fk, fd, b, id); } fn visit_block(&mut self, block: &'hir Block<'hir>) { - self.insert(block.span, block.hir_id, Node::Block(block)); + self.insert(block.hir_id, Node::Block(block)); self.with_parent(block.hir_id, |this| { intravisit::walk_block(this, block); }); } fn visit_local(&mut self, l: &'hir Local<'hir>) { - self.insert(l.span, l.hir_id, Node::Local(l)); + self.insert(l.hir_id, Node::Local(l)); self.with_parent(l.hir_id, |this| intravisit::walk_local(this, l)) } fn visit_lifetime(&mut self, lifetime: &'hir Lifetime) { - self.insert(lifetime.span, lifetime.hir_id, Node::Lifetime(lifetime)); + self.insert(lifetime.hir_id, Node::Lifetime(lifetime)); } fn visit_vis(&mut self, visibility: &'hir Visibility<'hir>) { match visibility.node { VisibilityKind::Public | VisibilityKind::Crate(_) | VisibilityKind::Inherited => {} VisibilityKind::Restricted { hir_id, .. } => { - self.insert(visibility.span, hir_id, Node::Visibility(visibility)); + self.insert(hir_id, Node::Visibility(visibility)); self.with_parent(hir_id, |this| { intravisit::walk_vis(this, visibility); }); @@ -538,29 +540,24 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { }); self.with_parent(parent, |this| { this.with_dep_node_owner(macro_def.hir_id.owner, macro_def, |this, hash| { - this.insert_with_hash( - macro_def.span, - macro_def.hir_id, - Node::MacroDef(macro_def), - hash, - ); + this.insert_with_hash(macro_def.hir_id, Node::MacroDef(macro_def), hash); }) }); } fn visit_variant(&mut self, v: &'hir Variant<'hir>, g: &'hir Generics<'hir>, item_id: HirId) { - self.insert(v.span, v.id, Node::Variant(v)); + self.insert(v.id, Node::Variant(v)); self.with_parent(v.id, |this| { // Register the constructor of this variant. if let Some(ctor_hir_id) = v.data.ctor_hir_id() { - this.insert(v.span, ctor_hir_id, Node::Ctor(&v.data)); + this.insert(ctor_hir_id, Node::Ctor(&v.data)); } intravisit::walk_variant(this, v, g, item_id); }); } fn visit_struct_field(&mut self, field: &'hir StructField<'hir>) { - self.insert(field.span, field.hir_id, Node::Field(field)); + self.insert(field.hir_id, Node::Field(field)); self.with_parent(field.hir_id, |this| { intravisit::walk_struct_field(this, field); }); @@ -569,7 +566,7 @@ 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: _, defaultness: _ } = *ii; + let TraitItemRef { id, ident: _, kind: _, defaultness: _ } = *ii; self.visit_nested_trait_item(id); } @@ -577,7 +574,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { fn visit_impl_item_ref(&mut self, ii: &'hir ImplItemRef<'hir>) { // 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: _, vis: _, defaultness: _ } = *ii; + let ImplItemRef { id, ident: _, kind: _, vis: _, defaultness: _ } = *ii; self.visit_nested_impl_item(id); } @@ -585,7 +582,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { fn visit_foreign_item_ref(&mut self, fi: &'hir ForeignItemRef<'hir>) { // 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: _, vis: _ } = *fi; + let ForeignItemRef { id, ident: _, vis: _ } = *fi; self.visit_nested_foreign_item(id); } diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index c2e99224d8b36..b6d271c70286b 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -267,19 +267,17 @@ impl<'hir> Map<'hir> { fn find_entry(&self, id: HirId) -> Option> { if id.local_id == ItemLocalId::from_u32(0) { - let owner = self.tcx.hir_owner(id.owner); - owner.map(|owner| Entry { parent: owner.parent, node: owner.node }) + let owner = self.tcx.hir_owner(id.owner)?; + Some(Entry { parent: owner.parent, node: owner.node }) } else { - let owner = self.tcx.hir_owner_nodes(id.owner); - owner.and_then(|owner| { - let node = owner.nodes[id.local_id].as_ref(); - // FIXME(eddyb) use a single generic type insted of having both - // `Entry` and `ParentedNode`, which are effectively the same. - // Alternatively, rewrite code using `Entry` to use `ParentedNode`. - node.map(|node| Entry { - parent: HirId { owner: id.owner, local_id: node.parent }, - node: node.node, - }) + let owner = self.tcx.hir_owner_nodes(id.owner)?; + let node = owner.nodes.get(id.local_id)?.as_ref()?; + // FIXME(eddyb) use a single generic type insted of having both + // `Entry` and `ParentedNode`, which are effectively the same. + // Alternatively, rewrite code using `Entry` to use `ParentedNode`. + Some(Entry { + parent: HirId { owner: id.owner, local_id: node.parent }, + node: node.node, }) } } @@ -451,11 +449,11 @@ impl<'hir> Map<'hir> { } } - pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) { + pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, HirId) { let hir_id = self.local_def_id_to_hir_id(module); match self.get_entry(hir_id).node { - Node::Item(&Item { span, kind: ItemKind::Mod(ref m), .. }) => (m, span, hir_id), - Node::Crate(item) => (&item.module, item.span, hir_id), + Node::Item(&Item { kind: ItemKind::Mod(ref m), .. }) => (m, hir_id), + Node::Crate(item) => (&item.module, hir_id), node => panic!("not a module: {:?}", node), } } @@ -853,61 +851,30 @@ impl<'hir> Map<'hir> { /// This is used by `tcx.get_span` pub fn span(&self, hir_id: HirId) -> Span { match self.find_entry(hir_id).map(|entry| entry.node) { - Some(Node::Param(param)) => param.span, - Some(Node::Item(item)) => match &item.kind { - ItemKind::Fn(sig, _, _) => sig.span, - _ => item.span, - }, - Some(Node::ForeignItem(foreign_item)) => foreign_item.span, - Some(Node::TraitItem(trait_item)) => match &trait_item.kind { - TraitItemKind::Fn(sig, _) => sig.span, - _ => trait_item.span, - }, - Some(Node::ImplItem(impl_item)) => match &impl_item.kind { - ImplItemKind::Fn(sig, _) => sig.span, - _ => impl_item.span, - }, - Some(Node::Variant(variant)) => variant.span, - Some(Node::Field(field)) => field.span, - Some(Node::AnonConst(constant)) => self.body(constant.body).value.span, - Some(Node::Expr(expr)) => expr.span, - Some(Node::Stmt(stmt)) => stmt.span, - Some(Node::PathSegment(seg)) => seg.ident.span, - Some(Node::Ty(ty)) => ty.span, - Some(Node::TraitRef(tr)) => tr.path.span, - Some(Node::Binding(pat)) => pat.span, - Some(Node::Pat(pat)) => pat.span, - Some(Node::Arm(arm)) => arm.span, - Some(Node::Block(block)) => block.span, - Some(Node::Ctor(..)) => match self.find(self.get_parent_node(hir_id)) { - Some(Node::Item(item)) => item.span, - Some(Node::Variant(variant)) => variant.span, - _ => unreachable!(), - }, - Some(Node::Lifetime(lifetime)) => lifetime.span, - Some(Node::GenericParam(param)) => param.span, - Some(Node::Visibility(&Spanned { - node: VisibilityKind::Restricted { ref path, .. }, - .. - })) => path.span, - Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v), - Some(Node::Local(local)) => local.span, - Some(Node::MacroDef(macro_def)) => macro_def.span, - Some(Node::Crate(item)) => item.span, - None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id), - } + Some(Node::Item(item)) => { + if let ItemKind::Fn(sig, _, _) = &item.kind { + return sig.span; + } + } + Some(Node::TraitItem(item)) => { + if let TraitItemKind::Fn(sig, _) = &item.kind { + return sig.span; + } + } + Some(Node::ImplItem(item)) => { + if let ImplItemKind::Fn(sig, _) = &item.kind { + return sig.span; + } + } + _ => {} + }; + self.tcx.hir_owner_spans(hir_id.owner)[hir_id.local_id] } /// Like `hir.span()`, but includes the body of function items /// (instead of just the function header) pub fn span_with_body(&self, hir_id: HirId) -> Span { - match self.find_entry(hir_id).map(|entry| entry.node) { - Some(Node::TraitItem(item)) => item.span, - Some(Node::ImplItem(impl_item)) => impl_item.span, - Some(Node::Item(item)) => item.span, - Some(_) => self.span(hir_id), - _ => bug!("hir::map::Map::span_with_body: id not in map: {:?}", hir_id), - } + self.tcx.hir_owner_spans(hir_id.owner)[hir_id.local_id] } pub fn span_if_local(&self, id: DefId) -> Option { diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index ae3b30217cc4a..080a87584e5e6 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -77,6 +77,7 @@ pub fn provide(providers: &mut Providers) { }; providers.hir_owner = |tcx, id| tcx.index_hir(LOCAL_CRATE).map[id].signature; providers.hir_owner_nodes = |tcx, id| tcx.index_hir(LOCAL_CRATE).map[id].with_bodies.as_deref(); + providers.hir_owner_spans = |tcx, id| tcx.hir_crate(LOCAL_CRATE).spans.get_owner(id); providers.fn_arg_names = |tcx, id| { let hir = tcx.hir(); let hir_id = hir.local_def_id_to_hir_id(id.expect_local()); diff --git a/compiler/rustc_middle/src/middle/region.rs b/compiler/rustc_middle/src/middle/region.rs index eb48198991c29..f6fa30823d1c0 100644 --- a/compiler/rustc_middle/src/middle/region.rs +++ b/compiler/rustc_middle/src/middle/region.rs @@ -184,7 +184,7 @@ impl Scope { // (This is the special case alluded to in the // doc-comment for this method) - let stmt_span = blk.stmts[first_statement_index.index()].span; + let stmt_span = tcx.hir().span(blk.stmts[first_statement_index.index()].hir_id); // To avoid issues with macro-generated spans, the span // of the statement must be nested in that of the block. diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 1e836d0a84253..a3fb77005bc92 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -89,6 +89,15 @@ rustc_queries! { desc { |tcx| "HIR owner items in `{}`", tcx.def_path_str(key.to_def_id()) } } + // Gives access to the HIR spans inside the HIR owner `key`. + // + // This can be conveniently accessed by methods on `tcx.hir()`. + // Avoid calling this query directly. + query hir_owner_spans(key: LocalDefId) -> &'tcx IndexVec { + eval_always + desc { |tcx| "HIR owner spans in `{}`", tcx.def_path_str(key.to_def_id()) } + } + /// Computes the `DefId` of the corresponding const parameter in case the `key` is a /// const argument and returns `None` otherwise. /// diff --git a/compiler/rustc_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index 3adcdbe591fc3..7b39244fd8a57 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -96,7 +96,10 @@ pub fn suggest_constraining_type_param( if def_id == tcx.lang_items().sized_trait() { // Type parameters are already `Sized` by default. - err.span_label(param.span, &format!("this type parameter needs to be `{}`", constraint)); + err.span_label( + tcx.hir().span(param.hir_id), + &format!("this type parameter needs to be `{}`", constraint), + ); return true; } let mut suggest_restrict = |span| { @@ -124,7 +127,7 @@ pub fn suggest_constraining_type_param( // | // replace with: `impl Foo + Bar` - suggest_restrict(param.span.shrink_to_hi()); + suggest_restrict(tcx.hir().span(param.hir_id).shrink_to_hi()); return true; } @@ -154,7 +157,7 @@ pub fn suggest_constraining_type_param( // fn foo(t: T) { ... } // - help: consider restricting this type parameter with `T: Foo` err.span_suggestion_verbose( - param.span.shrink_to_hi(), + tcx.hir().span(param.hir_id).shrink_to_hi(), &msg_restrict_type, format!(": {}", constraint), Applicability::MachineApplicable, diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index fe20925b38798..943b7ad0775c6 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -816,7 +816,7 @@ fn foo(&self) -> Self::T { String::new() } { if self.type_of(self.hir().local_def_id(item.id.hir_id)) == found { db.span_label( - item.span, + self.hir().span(item.id.hir_id), "associated type defaults can't be assumed inside the \ trait defining them", ); @@ -834,7 +834,8 @@ fn foo(&self) -> Self::T { String::new() } for item in &items[..] { if let hir::AssocItemKind::Type = item.kind { if self.type_of(self.hir().local_def_id(item.id.hir_id)) == found { - db.span_label(item.span, "expected this associated type"); + let item_span = self.hir().span(item.id.hir_id); + db.span_label(item_span, "expected this associated type"); return true; } } diff --git a/compiler/rustc_mir/src/borrow_check/diagnostics/region_name.rs b/compiler/rustc_mir/src/borrow_check/diagnostics/region_name.rs index cbca012824f82..b3d83aaaabf1f 100644 --- a/compiler/rustc_mir/src/borrow_check/diagnostics/region_name.rs +++ b/compiler/rustc_mir/src/borrow_check/diagnostics/region_name.rs @@ -638,7 +638,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { // doesn't happen, even in erroneous // programs. Else we should use delay-span-bug. span_bug!( - hir_arg.span(), + self.infcx.tcx.hir().span(hir_arg.id()), "unmatched subst and hir arg: found {:?} vs {:?}", kind, hir_arg, diff --git a/compiler/rustc_mir/src/transform/mod.rs b/compiler/rustc_mir/src/transform/mod.rs index 7f3b421cf76f6..a311b000c386a 100644 --- a/compiler/rustc_mir/src/transform/mod.rs +++ b/compiler/rustc_mir/src/transform/mod.rs @@ -10,7 +10,7 @@ use rustc_middle::mir::visit::Visitor as _; use rustc_middle::mir::{traversal, Body, ConstQualifs, MirPhase, Promoted}; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, TyCtxt, TypeFoldable}; -use rustc_span::{Span, Symbol}; +use rustc_span::Symbol; use std::borrow::Cow; pub mod add_call_guards; @@ -117,7 +117,6 @@ fn mir_keys(tcx: TyCtxt<'_>, krate: CrateNum) -> FxHashSet { _: Symbol, _: &'tcx hir::Generics<'tcx>, _: hir::HirId, - _: Span, ) { if let hir::VariantData::Tuple(_, hir_id) = *v { self.set.insert(self.tcx.hir().local_def_id(hir_id)); diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index 996615995259d..bb3ace680c2fe 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -154,7 +154,8 @@ fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam) -> Body<'_ // C-variadic fns also have a `VaList` input that's not listed in `fn_sig` // (as it's created inside the body itself, not passed in from outside). let ty = if fn_sig.c_variadic && index == fn_sig.inputs().len() { - let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(arg.span)); + let span = tcx.hir().span(arg.hir_id); + let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span)); tcx.type_of(va_list_did).subst(tcx, &[tcx.lifetimes.re_erased.into()]) } else { @@ -797,10 +798,12 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { argument_scope: region::Scope, ast_body: &'tcx hir::Expr<'tcx>, ) -> BlockAnd<()> { + let tcx = self.hir.tcx(); + // Allocate locals for the function arguments for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() { let source_info = - SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span)); + SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| tcx.hir().span(arg.pat.hir_id))); let arg_local = self.local_decls.push(LocalDecl::with_source_info(ty, source_info)); // If this is a simple binding pattern, give debuginfo a nice name. @@ -858,8 +861,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { if let Some(Node::Binding(pat)) = tcx_hir.find(var_id) { if let hir::PatKind::Binding(_, _, ident, _) = pat.kind { name = ident.name; + let pat_span = tcx_hir.span(pat.hir_id); match hir_typeck_results - .extract_binding_mode(tcx.sess, pat.hir_id, pat.span) + .extract_binding_mode(tcx.sess, pat.hir_id, pat_span) { Some(ty::BindByValue(hir::Mutability::Mut)) => { mutability = Mutability::Mut; @@ -903,7 +907,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // Make sure we drop (parts of) the argument even when not matched on. self.schedule_drop( - arg_opt.as_ref().map_or(ast_body.span, |arg| arg.pat.span), + arg_opt.as_ref().map_or(ast_body.span, |arg| tcx_hir.span(arg.pat.hir_id)), argument_scope, local, DropKind::Value, diff --git a/compiler/rustc_mir_build/src/thir/cx/block.rs b/compiler/rustc_mir_build/src/thir/cx/block.rs index 980888df7fee4..caea4bd663b4c 100644 --- a/compiler/rustc_mir_build/src/thir/cx/block.rs +++ b/compiler/rustc_mir_build/src/thir/cx/block.rs @@ -17,11 +17,12 @@ impl<'tcx> Mirror<'tcx> for &'tcx hir::Block<'tcx> { let stmts = mirror_stmts(cx, self.hir_id.local_id, &*self.stmts); let opt_destruction_scope = cx.region_scope_tree.opt_destruction_scope(self.hir_id.local_id); + let span = cx.tcx.hir().span(self.hir_id); Block { targeted_by_break: self.targeted_by_break, region_scope: region::Scope { id: self.hir_id.local_id, data: region::ScopeData::Node }, opt_destruction_scope, - span: self.span, + span, stmts, expr: self.expr.to_ref(), safety_mode: match self.rules { @@ -106,12 +107,8 @@ crate fn to_expr_ref<'a, 'tcx>( block: &'tcx hir::Block<'tcx>, ) -> ExprRef<'tcx> { let block_ty = cx.typeck_results().node_type(block.hir_id); + let span = cx.tcx.hir().span(block.hir_id); let temp_lifetime = cx.region_scope_tree.temporary_scope(block.hir_id.local_id); - let expr = Expr { - ty: block_ty, - temp_lifetime, - span: block.span, - kind: ExprKind::Block { body: block }, - }; + let expr = Expr { ty: block_ty, temp_lifetime, span, kind: ExprKind::Block { body: block } }; expr.to_ref() } diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 417f9bded0988..27cb2baf9591b 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -783,7 +783,7 @@ fn convert_arm<'tcx>(cx: &mut Cx<'_, 'tcx>, arm: &'tcx hir::Arm<'tcx>) -> Arm<'t body: arm.body.to_ref(), lint_level: LintLevel::Explicit(arm.hir_id), scope: region::Scope { id: arm.hir_id.local_id, data: region::ScopeData::Node }, - span: arm.span, + span: cx.tcx.hir().span(arm.hir_id), } } 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 a70c1a28176cd..9c2cea5fe767a 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -65,7 +65,7 @@ impl<'tcx> Visitor<'tcx> for MatchVisitor<'_, 'tcx> { intravisit::walk_local(self, loc); let (msg, sp) = match loc.source { - hir::LocalSource::Normal => ("local binding", Some(loc.span)), + hir::LocalSource::Normal => ("local binding", Some(self.tcx.hir().span(loc.hir_id))), hir::LocalSource::ForLoopDesugar => ("`for` loop binding", None), hir::LocalSource::AsyncFn => ("async fn binding", None), hir::LocalSource::AwaitDesugar => ("`await` future binding", None), @@ -141,7 +141,8 @@ impl<'tcx> MatchVisitor<'_, 'tcx> { let pattern: &_ = cx.pattern_arena.alloc(expand_pattern(pattern)); if !patcx.errors.is_empty() { *have_errors = true; - patcx.report_inlining_errors(pat.span); + let pat_span = self.tcx.hir().span(pat.hir_id); + patcx.report_inlining_errors(pat_span); } (pattern, pattern_ty) } @@ -226,9 +227,10 @@ impl<'tcx> MatchVisitor<'_, 'tcx> { } let joined_patterns = joined_uncovered_patterns(&witnesses); + let pat_span = self.tcx.hir().span(pat.hir_id); let mut err = struct_span_err!( self.tcx.sess, - pat.span, + pat_span, E0005, "refutable pattern in {}: {} not covered", origin, @@ -242,7 +244,7 @@ impl<'tcx> MatchVisitor<'_, 'tcx> { false } _ => { - err.span_label(pat.span, pattern_not_covered_label(&witnesses, &joined_patterns)); + err.span_label(pat_span, pattern_not_covered_label(&witnesses, &joined_patterns)); true } }; @@ -281,13 +283,14 @@ fn const_not_var( path: &hir::Path<'_>, ) { let descr = path.res.descr(); + let pat_span = tcx.hir().span(pat.hir_id); err.span_label( - pat.span, + pat_span, format!("interpreted as {} {} pattern, not a new variable", path.res.article(), descr,), ); err.span_suggestion( - pat.span, + pat_span, "introduce a variable instead", format!("{}_var", path.segments[0].ident).to_lowercase(), // Cannot use `MachineApplicable` as it's not really *always* correct @@ -304,8 +307,9 @@ fn const_not_var( fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>) { pat.walk_always(|p| { if let hir::PatKind::Binding(_, _, ident, None) = p.kind { + let span = cx.tcx.hir().span(p.hir_id); if let Some(ty::BindByValue(hir::Mutability::Not)) = - cx.typeck_results.extract_binding_mode(cx.tcx.sess, p.hir_id, p.span) + cx.typeck_results.extract_binding_mode(cx.tcx.sess, p.hir_id, span) { let pat_ty = cx.typeck_results.pat_ty(p).peel_refs(); if let ty::Adt(edef, _) = pat_ty.kind() { @@ -317,7 +321,7 @@ fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pa cx.tcx.struct_span_lint_hir( BINDINGS_WITH_VARIANT_NAME, p.hir_id, - p.span, + span, |lint| { let ty_path = cx.tcx.def_path_str(edef.did); lint.build(&format!( @@ -327,7 +331,7 @@ fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pa )) .code(error_code!(E0170)) .span_suggestion( - p.span, + span, "to match on the variant, qualify the path", format!("{}::{}", ty_path, ident), Applicability::MachineApplicable, @@ -616,17 +620,19 @@ fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_ hir::PatKind::Binding(.., name, Some(sub)) => (*name, sub), _ => return, }; - let binding_span = pat.span.with_hi(name.span.hi()); + let pat_span = cx.tcx.hir().span(pat.hir_id); + let binding_span = pat_span.with_hi(name.span.hi()); let typeck_results = cx.typeck_results; let sess = cx.tcx.sess; // Get the binding move, extract the mutability if by-ref. - let mut_outer = match typeck_results.extract_binding_mode(sess, pat.hir_id, pat.span) { - Some(ty::BindByValue(_)) if is_binding_by_move(cx, pat.hir_id, pat.span) => { + let mut_outer = match typeck_results.extract_binding_mode(sess, pat.hir_id, pat_span) { + Some(ty::BindByValue(_)) if is_binding_by_move(cx, pat.hir_id, pat_span) => { // We have `x @ pat` where `x` is by-move. Reject all borrows in `pat`. let mut conflicts_ref = Vec::new(); - sub.each_binding(|_, hir_id, span, _| { + sub.each_binding(|_, hir_id, _| { + let span = cx.tcx.hir().span(hir_id); match typeck_results.extract_binding_mode(sess, hir_id, span) { Some(ty::BindByValue(_)) | None => {} Some(ty::BindByReference(_)) => conflicts_ref.push(span), @@ -638,7 +644,7 @@ fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_ name, typeck_results.node_type(pat.hir_id), ); - sess.struct_span_err(pat.span, "borrow of moved value") + sess.struct_span_err(pat_span, "borrow of moved value") .span_label(binding_span, format!("value moved into `{}` here", name)) .span_label(binding_span, occurs_because) .span_labels(conflicts_ref, "value borrowed here after move") @@ -655,7 +661,8 @@ fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_ let mut conflicts_move = Vec::new(); let mut conflicts_mut_mut = Vec::new(); let mut conflicts_mut_ref = Vec::new(); - sub.each_binding(|_, hir_id, span, name| { + sub.each_binding(|_, hir_id, name| { + let span = cx.tcx.hir().span(hir_id); match typeck_results.extract_binding_mode(sess, hir_id, span) { Some(ty::BindByReference(mut_inner)) => match (mut_outer, mut_inner) { (Mutability::Not, Mutability::Not) => {} // Both sides are `ref`. @@ -673,7 +680,7 @@ fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_ if !conflicts_mut_mut.is_empty() { // Report mutability conflicts for e.g. `ref mut x @ Some(ref mut y)`. let mut err = sess - .struct_span_err(pat.span, "cannot borrow value as mutable more than once at a time"); + .struct_span_err(pat_span, "cannot borrow value as mutable more than once at a time"); err.span_label(binding_span, format!("first mutable borrow, by `{}`, occurs here", name)); for (span, name) in conflicts_mut_mut { err.span_label(span, format!("another mutable borrow, by `{}`, occurs here", name)); @@ -693,7 +700,7 @@ fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_ }; let msg = format!("cannot borrow value as {} because it is also borrowed as {}", also, primary); - let mut err = sess.struct_span_err(pat.span, &msg); + let mut err = sess.struct_span_err(pat_span, &msg); err.span_label(binding_span, format!("{} borrow, by `{}`, occurs here", primary, name)); for (span, name) in conflicts_mut_ref { err.span_label(span, format!("{} borrow, by `{}`, occurs here", also, name)); @@ -705,7 +712,7 @@ fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_ } else if !conflicts_move.is_empty() { // Report by-ref and by-move conflicts, e.g. `ref x @ y`. let mut err = - sess.struct_span_err(pat.span, "cannot move out of value because it is borrowed"); + sess.struct_span_err(pat_span, "cannot move out of value because it is borrowed"); err.span_label(binding_span, format!("value borrowed, by `{}`, here", name)); for (span, name) in conflicts_move { err.span_label(span, format!("value moved into `{}` here", name)); @@ -735,10 +742,11 @@ fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pa match pat.kind { hir::PatKind::Binding(.., ref subpat) => { if !self.bindings_allowed { + let pat_span = self.cx.tcx.hir().span(pat.hir_id); feature_err( &self.cx.tcx.sess.parse_sess, sym::bindings_after_at, - pat.span, + pat_span, "pattern bindings after an `@` are unstable", ) .emit(); diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index 7e9a3a37278b7..4dcd5c06d9d78 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -370,7 +370,8 @@ impl<'a, 'tcx> Pat<'tcx> { let result = pcx.lower_pattern(pat); if !pcx.errors.is_empty() { let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors); - tcx.sess.delay_span_bug(pat.span, &msg); + let pat_span = tcx.hir().span(pat.hir_id); + tcx.sess.delay_span_bug(pat_span, &msg); } debug!("Pat::from_hir({:?}) = {:?}", pat, result); result @@ -513,6 +514,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Pat<'tcx> { let mut ty = self.typeck_results.node_type(pat.hir_id); + let pat_span = self.tcx.hir().span(pat.hir_id); let kind = match pat.kind { hir::PatKind::Wild => PatKind::Wild, @@ -521,7 +523,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { hir::PatKind::Range(ref lo_expr, ref hi_expr, end) => { let (lo_expr, hi_expr) = (lo_expr.as_deref(), hi_expr.as_deref()); - let lo_span = lo_expr.map_or(pat.span, |e| e.span); + let lo_span = lo_expr.map_or(pat_span, |e| e.span); let lo = lo_expr.map(|e| self.lower_range_expr(e)); let hi = hi_expr.map(|e| self.lower_range_expr(e)); @@ -533,7 +535,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { "found bad range pattern `{:?}` outside of error recovery", (&lo, &hi), ); - self.tcx.sess.delay_span_bug(pat.span, msg); + self.tcx.sess.delay_span_bug(pat_span, msg); PatKind::Wild } }; @@ -543,7 +545,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { // constants somewhere. Have them on the range pattern. for end in &[lo, hi] { if let Some((_, Some(ascription))) = end { - let subpattern = Pat { span: pat.span, ty, kind: Box::new(kind) }; + let subpattern = Pat { span: pat_span, ty, kind: Box::new(kind) }; kind = PatKind::AscribeUserType { ascription: *ascription, subpattern }; } } @@ -552,7 +554,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { } hir::PatKind::Path(ref qpath) => { - return self.lower_path(qpath, pat.hir_id, pat.span); + return self.lower_path(qpath, pat.hir_id, pat_span); } hir::PatKind::Ref(ref subpattern, _) | hir::PatKind::Box(ref subpattern) => { @@ -560,13 +562,13 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { } hir::PatKind::Slice(ref prefix, ref slice, ref suffix) => { - self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix) + self.slice_or_array_pattern(pat_span, ty, prefix, slice, suffix) } hir::PatKind::Tuple(ref pats, ddpos) => { let tys = match ty.kind() { ty::Tuple(ref tys) => tys, - _ => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty), + _ => span_bug!(pat_span, "unexpected type for tuple pattern: {:?}", ty), }; let subpatterns = self.lower_tuple_subpats(pats, tys.len(), ddpos); PatKind::Leaf { subpatterns } @@ -615,11 +617,11 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { let res = self.typeck_results.qpath_res(qpath, pat.hir_id); let adt_def = match ty.kind() { ty::Adt(adt_def, _) => adt_def, - _ => span_bug!(pat.span, "tuple struct pattern not applied to an ADT {:?}", ty), + _ => span_bug!(pat_span, "tuple struct pattern not applied to an ADT {:?}", ty), }; let variant_def = adt_def.variant_of_res(res); let subpatterns = self.lower_tuple_subpats(pats, variant_def.fields.len(), ddpos); - self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns) + self.lower_variant_or_leaf(res, pat.hir_id, pat_span, ty, subpatterns) } hir::PatKind::Struct(ref qpath, ref fields, _) => { @@ -632,13 +634,13 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { }) .collect(); - self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns) + self.lower_variant_or_leaf(res, pat.hir_id, pat_span, ty, subpatterns) } hir::PatKind::Or(ref pats) => PatKind::Or { pats: self.lower_patterns(pats) }, }; - Pat { span: pat.span, ty, kind: Box::new(kind) } + Pat { span: pat_span, ty, kind: Box::new(kind) } } fn lower_tuple_subpats( diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 420c002c5fc46..0fc0322715a2b 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -898,7 +898,7 @@ impl Visitor<'tcx> for CheckAttrVisitor<'tcx> { self.check_attributes( generic_param.hir_id, generic_param.attrs, - &generic_param.span, + &self.tcx.hir().span(generic_param.hir_id), target, None, ); @@ -932,7 +932,8 @@ impl Visitor<'tcx> for CheckAttrVisitor<'tcx> { fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) { // When checking statements ignore expressions, they will be checked later. if let hir::StmtKind::Local(ref l) = stmt.kind { - self.check_attributes(l.hir_id, &l.attrs, &stmt.span, Target::Statement, None); + let stmt_span = self.tcx.hir().span(stmt.hir_id); + self.check_attributes(l.hir_id, &l.attrs, &stmt_span, Target::Statement, None); } intravisit::walk_stmt(self, stmt) } @@ -953,7 +954,8 @@ impl Visitor<'tcx> for CheckAttrVisitor<'tcx> { generics: &'tcx hir::Generics<'tcx>, item_id: HirId, ) { - self.check_attributes(variant.id, variant.attrs, &variant.span, Target::Variant, None); + let span = self.tcx.hir().span(variant.id); + self.check_attributes(variant.id, variant.attrs, &span, Target::Variant, None); intravisit::walk_variant(self, variant, generics, item_id) } } diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index c4fb0cf5b28dc..febc958ea12bd 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -142,7 +142,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { ) { let variant = match self.typeck_results().node_type(lhs.hir_id).kind() { ty::Adt(adt, _) => adt.variant_of_res(res), - _ => span_bug!(lhs.span, "non-ADT in struct pattern"), + _ => span_bug!(self.tcx.hir().span(lhs.hir_id), "non-ADT in struct pattern"), }; for pat in pats { if let PatKind::Wild = pat.pat.kind { @@ -241,7 +241,6 @@ impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> { _: Symbol, _: &hir::Generics<'_>, _: hir::HirId, - _: rustc_span::Span, ) { let has_repr_c = self.repr_has_repr_c; let inherited_pub_visibility = self.inherited_pub_visibility; @@ -626,7 +625,8 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> { id: hir::HirId, ) { if self.should_warn_about_variant(&variant) { - self.warn_dead_code(variant.id, variant.span, variant.ident.name, "constructed"); + let span = self.tcx.hir().span(variant.id); + self.warn_dead_code(variant.id, span, variant.ident.name, "constructed"); } else { intravisit::walk_variant(self, variant, g, id); } @@ -641,7 +641,8 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> { fn visit_struct_field(&mut self, field: &'tcx hir::StructField<'tcx>) { if self.should_warn_about_field(&field) { - self.warn_dead_code(field.hir_id, field.span, field.ident.name, "read"); + let span = self.tcx.hir().span(field.hir_id); + self.warn_dead_code(field.hir_id, span, field.ident.name, "read"); } intravisit::walk_struct_field(self, field); } diff --git a/compiler/rustc_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index 5ff631a24573f..faf538d5d8fe4 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -2,7 +2,7 @@ use rustc_ast::entry::EntryPointType; use rustc_errors::struct_span_err; use rustc_hir::def_id::{CrateNum, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc_hir::itemlikevisit::ItemLikeVisitor; -use rustc_hir::{ForeignItem, HirId, ImplItem, Item, ItemKind, TraitItem}; +use rustc_hir::{ForeignItem, HirId, ImplItem, Item, ItemKind, TraitItem, CRATE_HIR_ID}; use rustc_middle::hir::map::Map; use rustc_middle::ty::query::Providers; use rustc_middle::ty::TyCtxt; @@ -170,7 +170,7 @@ fn configure_main( } fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) { - let sp = tcx.hir().krate().item.span; + let sp = tcx.hir().span(CRATE_HIR_ID); if *tcx.sess.parse_sess.reached_eof.borrow() { // There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about // the missing `fn main()` then as it might have been hidden inside an unclosed block. diff --git a/compiler/rustc_passes/src/hir_stats.rs b/compiler/rustc_passes/src/hir_stats.rs index 1d02c9aa6375d..0f14f5f3c63ec 100644 --- a/compiler/rustc_passes/src/hir_stats.rs +++ b/compiler/rustc_passes/src/hir_stats.rs @@ -124,7 +124,7 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { hir_visit::walk_item(self, i) } - fn visit_mod(&mut self, m: &'v hir::Mod<'v>, _s: Span, n: hir::HirId) { + fn visit_mod(&mut self, m: &'v hir::Mod<'v>, n: hir::HirId) { self.record("Mod", Id::None, m); hir_visit::walk_mod(self, m, n) } @@ -174,11 +174,10 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { fk: hir_visit::FnKind<'v>, fd: &'v hir::FnDecl<'v>, b: hir::BodyId, - s: Span, id: hir::HirId, ) { self.record("FnDecl", Id::None, fd); - hir_visit::walk_fn(self, fk, fd, b, s, id) + hir_visit::walk_fn(self, fk, fd, b, id) } fn visit_where_predicate(&mut self, predicate: &'v hir::WherePredicate<'v>) { @@ -221,9 +220,9 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { hir_visit::walk_lifetime(self, lifetime) } - fn visit_qpath(&mut self, qpath: &'v hir::QPath<'v>, id: hir::HirId, span: Span) { + fn visit_qpath(&mut self, qpath: &'v hir::QPath<'v>, id: hir::HirId) { self.record("QPath", Id::None, qpath); - hir_visit::walk_qpath(self, qpath, id, span) + hir_visit::walk_qpath(self, qpath, id) } fn visit_path(&mut self, path: &'v hir::Path<'v>, _id: hir::HirId) { @@ -231,9 +230,9 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { hir_visit::walk_path(self, path) } - fn visit_path_segment(&mut self, path_span: Span, path_segment: &'v hir::PathSegment<'v>) { + fn visit_path_segment(&mut self, path_segment: &'v hir::PathSegment<'v>) { self.record("PathSegment", Id::None, path_segment); - hir_visit::walk_path_segment(self, path_span, path_segment) + hir_visit::walk_path_segment(self, path_segment) } fn visit_assoc_type_binding(&mut self, type_binding: &'v hir::TypeBinding<'v>) { diff --git a/compiler/rustc_passes/src/liveness.rs b/compiler/rustc_passes/src/liveness.rs index fcea1b29ec367..8e0e6a8513af5 100644 --- a/compiler/rustc_passes/src/liveness.rs +++ b/compiler/rustc_passes/src/liveness.rs @@ -295,7 +295,7 @@ impl IrMaps<'tcx> { } } - pat.each_binding(|_, hir_id, _, ident| { + pat.each_binding(|_, hir_id, ident| { self.add_live_node_for_node(hir_id, VarDefNode(ident.span)); self.add_variable(Local(LocalInfo { id: hir_id, @@ -368,7 +368,7 @@ impl<'tcx> Visitor<'tcx> for IrMaps<'tcx> { fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { let is_shorthand = matches!(param.pat.kind, rustc_hir::PatKind::Struct(..)); - param.pat.each_binding(|_bm, hir_id, _x, ident| { + param.pat.each_binding(|_bm, hir_id, ident| { let var = if is_shorthand { Local(LocalInfo { id: hir_id, name: ident.name, is_shorthand: true }) } else { @@ -549,7 +549,8 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { // In an or-pattern, only consider the first pattern; any later patterns // must have the same bindings, and we also consider the first pattern // to be the "authoritative" set of ids. - pat.each_binding_or_first(&mut |_, hir_id, pat_sp, ident| { + pat.each_binding_or_first(&mut |_, hir_id, ident| { + let pat_sp = self.ir.tcx.hir().span(hir_id); let ln = self.live_node(hir_id, pat_sp); let var = self.variable(hir_id, ident.span); self.init_from_succ(ln, succ); @@ -749,7 +750,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { loop { self.init_from_succ(self.closure_ln, succ); for param in body.params { - param.pat.each_binding(|_bm, hir_id, _x, ident| { + param.pat.each_binding(|_bm, hir_id, ident| { let var = self.variable(hir_id, ident.span); self.define(self.closure_ln, var); }) @@ -1467,7 +1468,8 @@ impl<'tcx> Liveness<'_, 'tcx> { // patterns so the suggestions to prefix with underscores will apply to those too. let mut vars: FxIndexMap)> = <_>::default(); - pat.each_binding(|_, hir_id, pat_sp, ident| { + pat.each_binding(|_, hir_id, ident| { + let pat_sp = self.ir.tcx.hir().span(hir_id); let ln = entry_ln.unwrap_or_else(|| self.live_node(hir_id, pat_sp)); let var = self.variable(hir_id, ident.span); let id_and_sp = (hir_id, pat_sp); diff --git a/compiler/rustc_passes/src/loops.rs b/compiler/rustc_passes/src/loops.rs index 9b4da71e5e961..cb5dfb9bca65d 100644 --- a/compiler/rustc_passes/src/loops.rs +++ b/compiler/rustc_passes/src/loops.rs @@ -144,6 +144,7 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { match destination.target_id { Ok(loop_id) => { if let Node::Block(block) = self.hir_map.find(loop_id).unwrap() { + let block_span = self.hir_map.span(block.hir_id); struct_span_err!( self.sess, e.span, @@ -151,7 +152,7 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { "`continue` pointing to a labeled block" ) .span_label(e.span, "labeled blocks cannot be `continue`'d") - .span_label(block.span, "labeled block the `continue` points to") + .span_label(block_span, "labeled block the `continue` points to") .emit(); } } diff --git a/compiler/rustc_passes/src/naked_functions.rs b/compiler/rustc_passes/src/naked_functions.rs index 788f1df328cc4..1aa533d6932f7 100644 --- a/compiler/rustc_passes/src/naked_functions.rs +++ b/compiler/rustc_passes/src/naked_functions.rs @@ -39,7 +39,6 @@ impl<'tcx> Visitor<'tcx> for CheckNakedFunctions<'tcx> { fk: FnKind<'v>, _fd: &'tcx hir::FnDecl<'tcx>, body_id: hir::BodyId, - span: Span, hir_id: HirId, ) { let ident_span; @@ -68,7 +67,7 @@ impl<'tcx> Visitor<'tcx> for CheckNakedFunctions<'tcx> { check_abi(self.tcx, hir_id, fn_header.abi, ident_span); check_no_patterns(self.tcx, body.params); check_no_parameters_use(self.tcx, body); - check_asm(self.tcx, hir_id, body, span); + check_asm(self.tcx, hir_id, body); } } } @@ -91,7 +90,7 @@ fn check_no_patterns(tcx: TyCtxt<'_>, params: &[hir::Param<'_>]) { _ => { tcx.sess .struct_span_err( - param.pat.span, + tcx.hir().span(param.pat.hir_id), "patterns not allowed in naked function parameters", ) .emit(); @@ -104,7 +103,7 @@ fn check_no_patterns(tcx: TyCtxt<'_>, params: &[hir::Param<'_>]) { fn check_no_parameters_use<'tcx>(tcx: TyCtxt<'tcx>, body: &'tcx hir::Body<'tcx>) { let mut params = hir::HirIdSet::default(); for param in body.params { - param.pat.each_binding(|_binding_mode, hir_id, _span, _ident| { + param.pat.each_binding(|_binding_mode, hir_id, _ident| { params.insert(hir_id); }); } @@ -146,12 +145,13 @@ impl<'tcx> Visitor<'tcx> for CheckParameters<'tcx> { } /// Checks that function body contains a single inline assembly block. -fn check_asm<'tcx>(tcx: TyCtxt<'tcx>, hir_id: HirId, body: &'tcx hir::Body<'tcx>, fn_span: Span) { +fn check_asm<'tcx>(tcx: TyCtxt<'tcx>, hir_id: HirId, body: &'tcx hir::Body<'tcx>) { let mut this = CheckInlineAssembly { tcx, items: Vec::new() }; this.visit_body(body); if let [(ItemKind::Asm, _)] = this.items[..] { // Ok. } else { + let fn_span = tcx.hir().span_with_body(hir_id); tcx.struct_span_lint_hir(UNSUPPORTED_NAKED_FUNCTIONS, hir_id, fn_span, |lint| { let mut diag = lint.build("naked functions must contain a single asm block"); let mut has_asm = false; @@ -308,10 +308,10 @@ impl<'tcx> Visitor<'tcx> for CheckInlineAssembly<'tcx> { match stmt.kind { StmtKind::Item(..) => {} StmtKind::Local(..) => { - self.items.push((ItemKind::NonAsm, stmt.span)); + self.items.push((ItemKind::NonAsm, self.tcx.hir().span(stmt.hir_id))); } StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => { - self.check_expr(expr, stmt.span); + self.check_expr(expr, self.tcx.hir().span(stmt.hir_id)); } } } diff --git a/compiler/rustc_passes/src/region.rs b/compiler/rustc_passes/src/region.rs index 1af79abe4b911..406a13633d174 100644 --- a/compiler/rustc_passes/src/region.rs +++ b/compiler/rustc_passes/src/region.rs @@ -17,7 +17,6 @@ use rustc_middle::middle::region::*; use rustc_middle::ty::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_span::source_map; -use rustc_span::Span; use std::mem; @@ -79,11 +78,7 @@ struct RegionResolutionVisitor<'tcx> { } /// Records the lifetime of a local variable as `cx.var_parent` -fn record_var_lifetime( - visitor: &mut RegionResolutionVisitor<'_>, - var_id: hir::ItemLocalId, - _sp: Span, -) { +fn record_var_lifetime(visitor: &mut RegionResolutionVisitor<'_>, var_id: hir::ItemLocalId) { match visitor.cx.var_parent { None => { // this can happen in extern fn declarations like @@ -180,7 +175,7 @@ fn resolve_pat<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, pat: &'tcx hir // If this is a binding then record the lifetime of that binding. if let PatKind::Binding(..) = pat.kind { - record_var_lifetime(visitor, pat.hir_id.local_id, pat.span); + record_var_lifetime(visitor, pat.hir_id.local_id); } debug!("resolve_pat - pre-increment {} pat = {:?}", visitor.expr_and_pat_count, pat); diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index def2a501cf475..2a8e11c8d5b88 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -381,10 +381,11 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { } fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) { + let var_span = self.tcx.hir().span(var.id); self.annotate( var.id, &var.attrs, - var.span, + var_span, AnnotationKind::Required, InheritDeprecation::Yes, |v| { @@ -392,7 +393,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { v.annotate( ctor_hir_id, &var.attrs, - var.span, + var_span, AnnotationKind::Required, InheritDeprecation::Yes, |_| {}, @@ -405,10 +406,11 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { } fn visit_struct_field(&mut self, s: &'tcx StructField<'tcx>) { + let span = self.tcx.hir().span(s.hir_id); self.annotate( s.hir_id, &s.attrs, - s.span, + span, AnnotationKind::Required, InheritDeprecation::Yes, |v| { @@ -431,10 +433,11 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { } fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef<'tcx>) { + let span = self.tcx.hir().span(md.hir_id); self.annotate( md.hir_id, &md.attrs, - md.span, + span, AnnotationKind::Required, InheritDeprecation::Yes, |_| {}, @@ -450,7 +453,8 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { _ => AnnotationKind::Prohibited, }; - self.annotate(p.hir_id, &p.attrs, p.span, kind, InheritDeprecation::No, |v| { + let span = self.tcx.hir().span(p.hir_id); + self.annotate(p.hir_id, &p.attrs, span, kind, InheritDeprecation::No, |v| { intravisit::walk_generic_param(v, p); }); } @@ -533,12 +537,14 @@ impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> { } fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) { - self.check_missing_stability(var.id, var.span); + let span = self.tcx.hir().span(var.id); + self.check_missing_stability(var.id, span); intravisit::walk_variant(self, var, g, item_id); } fn visit_struct_field(&mut self, s: &'tcx StructField<'tcx>) { - self.check_missing_stability(s.hir_id, s.span); + let span = self.tcx.hir().span(s.hir_id); + self.check_missing_stability(s.hir_id, span); intravisit::walk_struct_field(self, s); } @@ -548,7 +554,8 @@ impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> { } fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef<'tcx>) { - self.check_missing_stability(md.hir_id, md.span); + let span = self.tcx.hir().span(md.hir_id); + self.check_missing_stability(md.hir_id, span); } // Note that we don't need to `check_missing_stability` for default generic parameters, @@ -614,7 +621,7 @@ fn new_index(tcx: TyCtxt<'tcx>) -> Index<'tcx> { annotator.annotate( hir::CRATE_HIR_ID, &krate.item.attrs, - krate.item.span, + tcx.hir().span(hir::CRATE_HIR_ID), AnnotationKind::Required, InheritDeprecation::Yes, |v| intravisit::walk_crate(v, krate), @@ -817,7 +824,7 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { if tcx.stability().staged_api[&LOCAL_CRATE] { let krate = tcx.hir().krate(); let mut missing = MissingStabilityAnnotations { tcx, access_levels }; - missing.check_missing_stability(hir::CRATE_HIR_ID, krate.item.span); + missing.check_missing_stability(hir::CRATE_HIR_ID, tcx.hir().span(hir::CRATE_HIR_ID)); intravisit::walk_crate(&mut missing, krate); krate.visit_all_item_likes(&mut missing.as_deep_visitor()); } diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 1bcfdf0faf66a..6535ca920280f 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -809,7 +809,7 @@ impl Visitor<'tcx> for EmbargoVisitor<'tcx> { self.prev_level = orig_level; } - fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, _sp: Span, id: hir::HirId) { + fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, id: hir::HirId) { // This code is here instead of in visit_item so that the // crate module gets processed as well. if self.prev_level.is_some() { @@ -991,7 +991,7 @@ impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> { NestedVisitorMap::All(self.tcx.hir()) } - fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) { + fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _n: hir::HirId) { // Don't visit nested modules, since we run a separate visitor walk // for each module in `privacy_access_levels` } @@ -1024,16 +1024,17 @@ impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> { self.tcx.field_index(f.hir_id, self.typeck_results()) == vf_index }); let (use_ctxt, span) = match field { - Some(field) => (field.ident.span, field.span), + Some(field) => (field.ident.span, self.tcx.hir().span(field.hir_id)), None => (base.span, base.span), }; self.check_field(use_ctxt, span, adt, variant_field, true); } } else { for field in fields { + let field_span = self.tcx.hir().span(field.hir_id); let use_ctxt = field.ident.span; let index = self.tcx.field_index(field.hir_id, self.typeck_results()); - self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); + self.check_field(use_ctxt, field_span, adt, &variant.fields[index], false); } } } @@ -1049,7 +1050,8 @@ impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> { for field in fields { let use_ctxt = field.ident.span; let index = self.tcx.field_index(field.hir_id, self.typeck_results()); - self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); + let field_span = self.tcx.hir().span(field.hir_id); + self.check_field(use_ctxt, field_span, adt, &variant.fields[index], false); } } @@ -1120,7 +1122,7 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { NestedVisitorMap::All(self.tcx.hir()) } - fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) { + fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _n: hir::HirId) { // Don't visit nested modules, since we run a separate visitor walk // for each module in `privacy_access_levels` } @@ -1224,7 +1226,7 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { // we prohibit access to private statics from other crates, this allows to give // more code internal visibility at link time. (Access to private functions // is already prohibited by type privacy for function types.) - fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) { + fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId) { let def = match qpath { hir::QPath::Resolved(_, path) => match path.res { Res::Def(kind, def_id) => Some((kind, def_id)), @@ -1257,6 +1259,7 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { Some(name) => format!("{} `{}` is private", kind, name), None => format!("{} is private", kind), }; + let span = self.tcx.hir().span(id); sess.struct_span_err(span, &msg) .span_label(span, &format!("private {}", kind)) .emit(); @@ -1264,12 +1267,13 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { } } - intravisit::walk_qpath(self, qpath, id, span); + intravisit::walk_qpath(self, qpath, id); } // Check types of patterns. fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) { - if self.check_expr_pat_type(pattern.hir_id, pattern.span) { + let span = self.tcx.hir().span(pattern.hir_id); + if self.check_expr_pat_type(pattern.hir_id, span) { // Do not check nested patterns if the error already happened. return; } @@ -2052,7 +2056,8 @@ fn visibility(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Visibility { fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { // Check privacy of names not checked in previous compilation stages. let mut visitor = NamePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: None }; - let (module, span, hir_id) = tcx.hir().get_module(module_def_id); + let (module, hir_id) = tcx.hir().get_module(module_def_id); + let span = tcx.hir().span(hir_id); intravisit::walk_mod(&mut visitor, module, hir_id); diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 55623c9bd9cf6..4b4ca897da118 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -1661,7 +1661,8 @@ impl<'tcx> LifetimeContext<'_, 'tcx> { kind: hir::LifetimeParamKind::Elided, }) }) { - (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref)) + let span = self.tcx.hir().span(param.hir_id); + (span.shrink_to_lo(), format!("{}, ", lifetime_ref)) } else { suggests_in_band = true; (generics.span, format!("<{}>", lifetime_ref)) @@ -1733,7 +1734,10 @@ impl<'tcx> LifetimeContext<'_, 'tcx> { { let (span, span_type) = match &trait_ref.bound_generic_params { [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty), - [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail), + [.., bound] => ( + self.tcx.hir().span(bound.hir_id).shrink_to_hi(), + ForLifetimeSpanType::BoundTail, + ), }; self.missing_named_lifetime_spots .push(MissingLifetimeSpot::HigherRanked { span, span_type }); @@ -1844,7 +1848,8 @@ impl<'tcx> LifetimeContext<'_, 'tcx> { .. }) }) { - (param.span.shrink_to_lo(), "'a, ".to_string()) + let span = self.tcx.hir().span(param.hir_id); + (span.shrink_to_lo(), "'a, ".to_string()) } else { (generics.span, "<'a>".to_string()) } diff --git a/compiler/rustc_resolve/src/late/lifetimes.rs b/compiler/rustc_resolve/src/late/lifetimes.rs index d5ba6f3b53b21..acdea965bc0b3 100644 --- a/compiler/rustc_resolve/src/late/lifetimes.rs +++ b/compiler/rustc_resolve/src/late/lifetimes.rs @@ -477,7 +477,9 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { self.is_in_fn_syntax = true; let lifetime_span: Option = c.generic_params.iter().rev().find_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => Some(param.span), + GenericParamKind::Lifetime { .. } => { + Some(self.tcx.hir().span(param.hir_id)) + } _ => None, }); let (span, span_type) = if let Some(span) = lifetime_span { @@ -1033,8 +1035,9 @@ fn shadower_label(span: Span) -> Shadower { fn original_lifetime(span: Span) -> Original { Original { kind: ShadowKind::Lifetime, span } } -fn shadower_lifetime(param: &hir::GenericParam<'_>) -> Shadower { - Shadower { kind: ShadowKind::Lifetime, span: param.span } +fn shadower_lifetime(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) -> Shadower { + let span = tcx.hir().span(param.hir_id); + Shadower { kind: ShadowKind::Lifetime, span } } impl ShadowKind { @@ -1050,7 +1053,7 @@ fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &[hir::Generic let lifetime_params: Vec<_> = params .iter() .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)), + GenericParamKind::Lifetime { kind, .. } => Some((kind, tcx.hir().span(param.hir_id))), _ => None, }) .collect(); @@ -1376,8 +1379,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { in_band = true; } } + let param_span = self.tcx.hir().span(param.hir_id); if in_band { - Some(param.span) + Some(param_span) } else if generics.params.len() == 1 { // if sole lifetime, remove the entire `<>` brackets Some(generics.span) @@ -1385,9 +1389,11 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // if removing within `<>` brackets, we also want to // delete a leading or trailing comma as appropriate if i >= generics.params.len() - 1 { - Some(generics.params[i - 1].span.shrink_to_hi().to(param.span)) + let generic_span = self.tcx.hir().span(generics.params[i - 1].hir_id); + Some(generic_span.shrink_to_hi().to(param_span)) } else { - Some(param.span.to(generics.params[i + 1].span.shrink_to_lo())) + let generic_span = self.tcx.hir().span(generics.params[i + 1].hir_id); + Some(param_span.to(generic_span.shrink_to_lo())) } } } else { @@ -1545,7 +1551,8 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { hir_lifetime.name.ident(), )), Node::GenericParam(param) => { - Some((param.hir_id, param.span, param.name.ident())) + let span = self.tcx.hir().span(param.hir_id); + Some((param.hir_id, span, param.name.ident())) } _ => None, } { @@ -1602,7 +1609,8 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { hir_lifetime.name.ident(), )), Node::GenericParam(param) => { - Some((param.hir_id, param.span, param.name.ident())) + let span = self.tcx.hir().span(param.hir_id); + Some((param.hir_id, span, param.name.ident())) } _ => None, } { @@ -2549,17 +2557,15 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { if let hir::ParamName::Plain(_) = lifetime_i_name { let name = lifetime_i_name.ident().name; if name == kw::UnderscoreLifetime || name == kw::StaticLifetime { + let span_i = self.tcx.hir().span(lifetime_i.hir_id); let mut err = struct_span_err!( self.tcx.sess, - lifetime_i.span, + span_i, E0262, "invalid lifetime parameter name: `{}`", lifetime_i.name.ident(), ); - err.span_label( - lifetime_i.span, - format!("{} is a reserved lifetime name", name), - ); + err.span_label(span_i, format!("{} is a reserved lifetime name", name)); err.emit(); } } @@ -2567,15 +2573,17 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // It is a hard error to shadow a lifetime within the same scope. for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) { if lifetime_i_name == lifetime_j_name { + let span_i = self.tcx.hir().span(lifetime_i.hir_id); + let span_j = self.tcx.hir().span(lifetime_j.hir_id); struct_span_err!( self.tcx.sess, - lifetime_j.span, + span_j, E0263, "lifetime name `{}` declared twice in the same scope", lifetime_j.name.ident() ) - .span_label(lifetime_j.span, "declared twice") - .span_label(lifetime_i.span, "previous declaration here") + .span_label(span_j, "declared twice") + .span_label(span_i, "previous declaration here") .emit(); } } @@ -2592,10 +2600,11 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { ), hir::LifetimeName::Static => { self.insert_lifetime(lt, Region::Static); + let span_i = self.tcx.hir().span(lifetime_i.hir_id); self.tcx .sess .struct_span_warn( - lifetime_i.span.to(lt.span), + span_i.to(lt.span), &format!( "unnecessary lifetime parameter `{}`", lifetime_i.name.ident(), @@ -2639,7 +2648,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { self.tcx, label.name, original_label(label.span), - shadower_lifetime(¶m), + shadower_lifetime(self.tcx, ¶m), ); return; } @@ -2666,7 +2675,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { self.tcx, param.name.ident().name, original_lifetime(self.tcx.hir().span(hir_id)), - shadower_lifetime(¶m), + shadower_lifetime(self.tcx, ¶m), ); return; } @@ -2866,7 +2875,7 @@ fn insert_late_bound_lifetimes( // is, those would be potentially inputs to // projections if let Some(last_segment) = path.segments.last() { - self.visit_path_segment(path.span, last_segment); + self.visit_path_segment(last_segment); } } diff --git a/compiler/rustc_save_analysis/src/dump_visitor.rs b/compiler/rustc_save_analysis/src/dump_visitor.rs index 617a28ed51938..775188816f5fa 100644 --- a/compiler/rustc_save_analysis/src/dump_visitor.rs +++ b/compiler/rustc_save_analysis/src/dump_visitor.rs @@ -128,7 +128,7 @@ impl<'tcx> DumpVisitor<'tcx> { self.save_ctxt.lookup_def_id(ref_id) } - pub fn dump_crate_info(&mut self, name: &str, krate: &hir::Crate<'_>) { + pub fn dump_crate_info(&mut self, name: &str, _krate: &hir::Crate<'_>) { let source_file = self.tcx.sess.local_crate_source_file.as_ref(); let crate_root = source_file.map(|source_file| { let source_file = Path::new(source_file); @@ -151,7 +151,7 @@ impl<'tcx> DumpVisitor<'tcx> { }, crate_root: crate_root.unwrap_or_else(|| "".to_owned()), external_crates: self.save_ctxt.get_external_crates(), - span: self.span_from_span(krate.item.span), + span: self.span_from_span(self.tcx.hir().span(hir::CRATE_HIR_ID)), }; self.dumper.crate_prelude(data); @@ -376,7 +376,7 @@ impl<'tcx> DumpVisitor<'tcx> { self.nest_typeck_results(map.local_def_id(item.hir_id), |v| { let body = map.body(body); if let Some(fn_data) = v.save_ctxt.get_item_data(item) { - down_cast_data!(fn_data, DefData, item.span); + down_cast_data!(fn_data, DefData, v.tcx.hir().span(item.hir_id)); v.process_formals(body.params, &fn_data.qualname); v.process_generic_params(ty_params, &fn_data.qualname, item.hir_id); @@ -403,7 +403,7 @@ impl<'tcx> DumpVisitor<'tcx> { ) { self.nest_typeck_results(self.tcx.hir().local_def_id(item.hir_id), |v| { if let Some(var_data) = v.save_ctxt.get_item_data(item) { - down_cast_data!(var_data, DefData, item.span); + down_cast_data!(var_data, DefData, v.tcx.hir().span(item.hir_id)); v.dumper.dump_def(&access_from!(v.save_ctxt, item, item.hir_id), var_data); } v.visit_ty(&typ); @@ -463,7 +463,7 @@ impl<'tcx> DumpVisitor<'tcx> { def: &'tcx hir::VariantData<'tcx>, ty_params: &'tcx hir::Generics<'tcx>, ) { - debug!("process_struct {:?} {:?}", item, item.span); + debug!("process_struct {:?} {:?}", item, self.tcx.hir().span(item.hir_id)); let name = item.ident.to_string(); let qualname = format!( "::{}", @@ -539,7 +539,7 @@ impl<'tcx> DumpVisitor<'tcx> { None => return, Some(data) => data, }; - down_cast_data!(enum_data, DefData, item.span); + down_cast_data!(enum_data, DefData, self.tcx.hir().span(item.hir_id)); let access = access_from!(self.save_ctxt, item, item.hir_id); @@ -640,12 +640,13 @@ impl<'tcx> DumpVisitor<'tcx> { impl_items: &'tcx [hir::ImplItemRef<'tcx>], ) { if let Some(impl_data) = self.save_ctxt.get_item_data(item) { - if !self.span.filter_generated(item.span) { + let item_span = self.tcx.hir().span(item.hir_id); + if !self.span.filter_generated(item_span) { if let super::Data::RelationData(rel, imp) = impl_data { self.dumper.dump_relation(rel); self.dumper.dump_impl(imp); } else { - span_bug!(item.span, "unexpected data kind: {:?}", impl_data); + span_bug!(item_span, "unexpected data kind: {:?}", impl_data); } } } @@ -756,7 +757,7 @@ impl<'tcx> DumpVisitor<'tcx> { // `item` is the module in question, represented as an( item. fn process_mod(&mut self, item: &'tcx hir::Item<'tcx>) { if let Some(mod_data) = self.save_ctxt.get_item_data(item) { - down_cast_data!(mod_data, DefData, item.span); + down_cast_data!(mod_data, DefData, self.tcx.hir().span(item.hir_id)); self.dumper.dump_def(&access_from!(self.save_ctxt, item, item.hir_id), mod_data); } } @@ -822,8 +823,8 @@ impl<'tcx> DumpVisitor<'tcx> { if let hir::QPath::Resolved(_, path) = path { self.write_sub_paths_truncated(path); } - down_cast_data!(struct_lit_data, RefData, ex.span); - if !generated_code(ex.span) { + down_cast_data!(struct_lit_data, RefData, self.tcx.hir().span(ex.hir_id)); + if !generated_code(self.tcx.hir().span(ex.hir_id)) { self.dumper.dump_ref(struct_lit_data); } @@ -847,10 +848,11 @@ impl<'tcx> DumpVisitor<'tcx> { seg: &'tcx hir::PathSegment<'tcx>, args: &'tcx [hir::Expr<'tcx>], ) { - debug!("process_method_call {:?} {:?}", ex, ex.span); + let ex_span = self.tcx.hir().span(ex.hir_id); + debug!("process_method_call {:?} {:?}", ex, ex_span); if let Some(mcd) = self.save_ctxt.get_expr_data(ex) { - down_cast_data!(mcd, RefData, ex.span); - if !generated_code(ex.span) { + down_cast_data!(mcd, RefData, ex_span); + if !generated_code(ex_span) { self.dumper.dump_ref(mcd); } } @@ -974,7 +976,9 @@ impl<'tcx> DumpVisitor<'tcx> { /// If the span is not macro-generated, do nothing, else use callee and /// callsite spans to record macro definition and use data, using the /// mac_uses and mac_defs sets to prevent multiples. - fn process_macro_use(&mut self, _span: Span) { + fn process_macro_use(&mut self, _hir_id: hir::HirId) { + //let span = self.tcx.hir().span(_hir_id); + // // FIXME if we're not dumping the defs (see below), there is no point // dumping refs either. // let source_span = span.source_callsite(); @@ -1011,8 +1015,8 @@ impl<'tcx> DumpVisitor<'tcx> { } fn process_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>, trait_id: DefId) { - self.process_macro_use(trait_item.span); - let vis_span = trait_item.span.shrink_to_lo(); + self.process_macro_use(trait_item.hir_id); + let vis_span = self.tcx.hir().span(trait_item.hir_id).shrink_to_lo(); match trait_item.kind { hir::TraitItemKind::Const(ref ty, body) => { let body = body.map(|b| &self.tcx.hir().body(b).value); @@ -1038,7 +1042,7 @@ impl<'tcx> DumpVisitor<'tcx> { trait_item.ident, &trait_item.generics, &respan, - trait_item.span, + self.tcx.hir().span(trait_item.hir_id), ); } hir::TraitItemKind::Type(ref bounds, ref default_ty) => { @@ -1062,7 +1066,7 @@ impl<'tcx> DumpVisitor<'tcx> { span, name, qualname, - value: self.span.snippet(trait_item.span), + value: self.span.snippet(self.tcx.hir().span(trait_item.hir_id)), parent: Some(id_from_def_id(trait_id)), children: vec![], decl_id: None, @@ -1090,7 +1094,7 @@ impl<'tcx> DumpVisitor<'tcx> { } fn process_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>, impl_id: DefId) { - self.process_macro_use(impl_item.span); + self.process_macro_use(impl_item.hir_id); match impl_item.kind { hir::ImplItemKind::Const(ref ty, body) => { let body = self.tcx.hir().body(body); @@ -1112,7 +1116,7 @@ impl<'tcx> DumpVisitor<'tcx> { impl_item.ident, &impl_item.generics, &impl_item.vis, - impl_item.span, + self.tcx.hir().span(impl_item.hir_id), ); } hir::ImplItemKind::TyAlias(ref ty) => { @@ -1130,7 +1134,9 @@ impl<'tcx> DumpVisitor<'tcx> { format!("::{}", self.tcx.def_path_str(self.tcx.hir().local_def_id(id).to_def_id())); let sm = self.tcx.sess.source_map(); - let filename = sm.span_to_filename(krate.item.span); + let span = self.tcx.hir().span(hir::CRATE_HIR_ID); + let filename = sm.span_to_filename(span); + let span = self.span_from_span(span); let data_id = id_from_hir_id(id, &self.save_ctxt); let children = krate .item @@ -1139,7 +1145,6 @@ impl<'tcx> DumpVisitor<'tcx> { .iter() .map(|i| id_from_hir_id(i.id, &self.save_ctxt)) .collect(); - let span = self.span_from_span(krate.item.span); self.dumper.dump_def( &Access { public: true, reachable: true }, @@ -1181,7 +1186,7 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { } fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { - self.process_macro_use(item.span); + self.process_macro_use(item.hir_id); match item.kind { hir::ItemKind::Use(path, hir::UseKind::Single) => { let sub_span = path.segments.last().unwrap().ident.span; @@ -1219,8 +1224,9 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { // Otherwise it's a span with wrong macro expansion info, which // we don't want to track anyway, since it's probably macro-internal `use` - if let Some(sub_span) = self.span.sub_span_of_star(item.span) { - if !self.span.filter_generated(item.span) { + let item_span = self.tcx.hir().span(item.hir_id); + if let Some(sub_span) = self.span.sub_span_of_star(item_span) { + if !self.span.filter_generated(item_span) { let access = access_from!(self.save_ctxt, item, item.hir_id); let span = self.span_from_span(sub_span); let parent = self @@ -1361,10 +1367,10 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { } fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) { - self.process_macro_use(t.span); + self.process_macro_use(t.hir_id); match t.kind { hir::TyKind::Path(ref path) => { - if generated_code(t.span) { + if generated_code(self.tcx.hir().span(t.hir_id)) { return; } @@ -1381,7 +1387,7 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { if let hir::QPath::Resolved(_, path) = path { self.write_sub_paths_truncated(path); } - intravisit::walk_qpath(self, path, t.hir_id, t.span); + intravisit::walk_qpath(self, path, t.hir_id); } hir::TyKind::Array(ref ty, ref anon_const) => { self.visit_ty(ty); @@ -1402,7 +1408,7 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) { debug!("visit_expr {:?}", ex.kind); - self.process_macro_use(ex.span); + self.process_macro_use(ex.hir_id); match ex.kind { hir::ExprKind::Struct(ref path, ref fields, ref rest) => { let hir_expr = self.save_ctxt.tcx.hir().expect_expr(ex.hir_id); @@ -1423,8 +1429,9 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { self.visit_expr(&sub_ex); if let Some(field_data) = self.save_ctxt.get_expr_data(ex) { - down_cast_data!(field_data, RefData, ex.span); - if !generated_code(ex.span) { + let ex_span = self.tcx.hir().span(ex.hir_id); + down_cast_data!(field_data, RefData, ex_span); + if !generated_code(ex_span) { self.dumper.dump_ref(field_data); } } @@ -1463,7 +1470,7 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { } fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { - self.process_macro_use(p.span); + self.process_macro_use(p.hir_id); self.process_pat(p); } @@ -1475,17 +1482,17 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { self.visit_expr(&arm.body); } - fn visit_qpath(&mut self, path: &'tcx hir::QPath<'tcx>, id: hir::HirId, _: Span) { + fn visit_qpath(&mut self, path: &'tcx hir::QPath<'tcx>, id: hir::HirId) { self.process_path(id, path); } fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) { - self.process_macro_use(s.span); + self.process_macro_use(s.hir_id); intravisit::walk_stmt(self, s) } fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { - self.process_macro_use(l.span); + self.process_macro_use(l.hir_id); self.process_var_decl(&l.pat); // Just walk the initialiser and type (don't want to walk the pattern again). @@ -1499,7 +1506,7 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { match item.kind { hir::ForeignItemKind::Fn(decl, _, ref generics) => { if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) { - down_cast_data!(fn_data, DefData, item.span); + down_cast_data!(fn_data, DefData, self.tcx.hir().span(item.hir_id)); self.process_generic_params(generics, &fn_data.qualname, item.hir_id); self.dumper.dump_def(&access, fn_data); @@ -1515,7 +1522,7 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { } hir::ForeignItemKind::Static(ref ty, _) => { if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) { - down_cast_data!(var_data, DefData, item.span); + down_cast_data!(var_data, DefData, self.tcx.hir().span(item.hir_id)); self.dumper.dump_def(&access, var_data); } @@ -1523,7 +1530,7 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { } hir::ForeignItemKind::Type => { if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) { - down_cast_data!(var_data, DefData, item.span); + down_cast_data!(var_data, DefData, self.tcx.hir().span(item.hir_id)); self.dumper.dump_def(&access, var_data); } } diff --git a/compiler/rustc_save_analysis/src/lib.rs b/compiler/rustc_save_analysis/src/lib.rs index 056c0b3d9d513..bbd319630eb5b 100644 --- a/compiler/rustc_save_analysis/src/lib.rs +++ b/compiler/rustc_save_analysis/src/lib.rs @@ -301,8 +301,13 @@ impl<'tcx> SaveContext<'tcx> { let name = item.ident.to_string(); let qualname = format!("::{}", self.tcx.def_path_str(def_id)); filter!(self.span_utils, item.ident.span); - let value = - enum_def_to_string(def, generics, item.ident.name, item.span, &item.vis); + let value = enum_def_to_string( + def, + generics, + item.ident.name, + self.tcx.hir().span(item.hir_id), + &item.vis, + ); Some(Data::DefData(Def { kind: DefKind::Enum, id: id_from_def_id(def_id), @@ -892,7 +897,9 @@ impl<'l> Visitor<'l> for PathCollector<'l> { hir::PatKind::Binding(bm, _, ident, _) => { debug!( "PathCollector, visit ident in pat {}: {:?} {:?}", - ident, p.span, ident.span + ident, + self.tcx.hir().span(p.hir_id), + ident.span ); let immut = match bm { // Even if the ref is mut, you can't change the ref, only diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index a439bb892f8e7..2328c8f09a504 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -793,21 +793,20 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { .params .iter() .map(|arg| { - if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } = - *arg.pat - { + let span = hir.span(arg.pat.hir_id); + if let hir::PatKind::Tuple(ref args, _) = arg.pat.kind { Some(ArgKind::Tuple( Some(span), args.iter() .map(|pat| { - sm.span_to_snippet(pat.span) + sm.span_to_snippet(hir.span(pat.hir_id)) .ok() .map(|snippet| (snippet, "_".to_owned())) }) .collect::>>()?, )) } else { - let name = sm.span_to_snippet(arg.pat.span).ok()?; + let name = sm.span_to_snippet(span).ok()?; Some(ArgKind::Arg(name, "_".to_owned())) } }) @@ -1737,7 +1736,8 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { None => return, }; for param in generics.params { - if param.span != span + let param_span = self.tcx.hir().span(param.hir_id); + if param_span != span || param.bounds.iter().any(|bound| { bound.trait_ref().and_then(|trait_ref| trait_ref.trait_def_id()) == self.tcx.lang_items().sized_trait() @@ -1767,9 +1767,9 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { }; visitor.visit_item(item); if !visitor.invalid_spans.is_empty() { - let mut multispan: MultiSpan = param.span.into(); + let mut multispan: MultiSpan = param_span.into(); multispan.push_span_label( - param.span, + param_span, format!("this could be changed to `{}: ?Sized`...", param.name.ident()), ); for sp in visitor.invalid_spans { diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index 79fea83a6674d..6b9a21cb235dc 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -259,7 +259,7 @@ fn suggest_restriction( match generics .params .iter() - .map(|p| p.bounds_span().unwrap_or(p.span)) + .map(|p| p.bounds_span().unwrap_or(tcx.hir().span(p.hir_id))) .filter(|&span| generics.span.contains(span) && span.desugaring_kind().is_none()) .max_by_key(|span| span.hi()) { @@ -888,7 +888,8 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { // no return, suggest removal of semicolon on last statement. // Once that is added, close #54771. if let Some(ref stmt) = blk.stmts.last() { - let sp = self.tcx.sess.source_map().end_point(stmt.span); + let span = self.tcx.hir().span(stmt.hir_id); + let sp = self.tcx.sess.source_map().end_point(span); err.span_label(sp, "consider removing this semicolon"); } } diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index 3f58fd72f409c..c5fae268da0da 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -205,7 +205,7 @@ fn extend_cause_with_original_assoc_item_obligation<'tcx>( let fix_span = |impl_item_ref: &hir::ImplItemRef<'_>| match tcx.hir().impl_item(impl_item_ref.id).kind { hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::TyAlias(ty) => ty.span, - _ => impl_item_ref.span, + _ => tcx.hir().span(impl_item_ref.id.hir_id), }; // It is fine to skip the binder as we don't care about regions here. diff --git a/compiler/rustc_typeck/src/astconv/generics.rs b/compiler/rustc_typeck/src/astconv/generics.rs index 1100401ed12dd..bf19580b88ec1 100644 --- a/compiler/rustc_typeck/src/astconv/generics.rs +++ b/compiler/rustc_typeck/src/astconv/generics.rs @@ -27,9 +27,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { help: Option<&str>, ) { let sess = tcx.sess; + let arg_span = tcx.hir().span(arg.id()); let mut err = struct_span_err!( sess, - arg.span(), + arg_span, E0747, "{} provided when a {} was expected", arg.descr(), @@ -49,8 +50,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { GenericParamDefKind::Const { .. }, ) => { let suggestions = vec![ - (arg.span().shrink_to_lo(), String::from("{ ")), - (arg.span().shrink_to_hi(), String::from(" }")), + (arg_span.shrink_to_lo(), String::from("{ ")), + (arg_span.shrink_to_hi(), String::from(" }")), ]; err.multipart_suggestion( "if this generic argument was intended as a const parameter, \ @@ -66,7 +67,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let snippet = sess.source_map().span_to_snippet(tcx.hir().span(len.hir_id)); if let Ok(snippet) = snippet { err.span_suggestion( - arg.span(), + arg_span, "array type provided where a `usize` was expected, try", format!("{{ {} }}", snippet), Applicability::MaybeIncorrect, @@ -403,7 +404,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } if position != GenericArgPosition::Type && !args.bindings.is_empty() { - AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span); + AstConv::prohibit_assoc_ty_binding(tcx, tcx.hir().span(args.bindings[0].hir_id)); } let explicit_late_bound = @@ -450,7 +451,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let (spans, labels): (Vec, Vec) = args.args [offset + permitted..offset + provided] .iter() - .map(|arg| (arg.span(), format!("unexpected {} argument", arg.short_descr()))) + .map(|arg| { + ( + tcx.hir().span(arg.id()), + format!("unexpected {} argument", arg.short_descr()), + ) + }) .unzip(); unexpected_spans.extend(spans.clone()); (spans, labels) @@ -553,7 +559,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .args .iter() .filter_map(|arg| match arg { - GenericArg::Type(_) | GenericArg::Const(_) => Some(arg.span()), + GenericArg::Type(_) | GenericArg::Const(_) => Some(tcx.hir().span(arg.id())), _ => None, }) .collect::>(); @@ -599,7 +605,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let msg = "cannot specify lifetime arguments explicitly \ if late bound lifetime parameters are present"; let note = "the late bound lifetime parameter is introduced here"; - let span = args.args[0].span(); + let span = tcx.hir().span(args.args[0].id()); if position == GenericArgPosition::Value && arg_counts.lifetimes != param_counts.lifetimes { diff --git a/compiler/rustc_typeck/src/astconv/mod.rs b/compiler/rustc_typeck/src/astconv/mod.rs index 878993d512cee..b20e718694055 100644 --- a/compiler/rustc_typeck/src/astconv/mod.rs +++ b/compiler/rustc_typeck/src/astconv/mod.rs @@ -401,10 +401,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => { if has_default { + let arg_id = arg.id(); tcx.check_optional_stability( param.def_id, - Some(arg.id()), - arg.span(), + Some(arg_id), + tcx.hir().span(arg_id), |_, _| { // Default generic parameters may not be marked // with stability attributes, i.e. when the @@ -547,7 +548,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ConvertedBindingKind::Constraint(bounds) } }; - ConvertedBinding { item_name: binding.ident, kind, span: binding.span } + ConvertedBinding { + item_name: binding.ident, + kind, + span: tcx.hir().span(binding.hir_id), + } }) .collect(); @@ -1777,7 +1782,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } err_for_ct = true; has_err = true; - (ct.span, "const") + (self.tcx().hir().span(ct.value.hir_id), "const") } }; let mut err = struct_span_err!( @@ -1797,7 +1802,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // Only emit the first error to avoid overloading the user with error messages. if let [binding, ..] = segment.generic_args().bindings { has_err = true; - Self::prohibit_assoc_ty_binding(self.tcx(), binding.span); + Self::prohibit_assoc_ty_binding(self.tcx(), self.tcx().hir().span(binding.hir_id)); } } has_err diff --git a/compiler/rustc_typeck/src/check/_match.rs b/compiler/rustc_typeck/src/check/_match.rs index 6467e04407939..3c4a27e68b363 100644 --- a/compiler/rustc_typeck/src/check/_match.rs +++ b/compiler/rustc_typeck/src/check/_match.rs @@ -348,7 +348,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } if let Local(hir::Local { ty: Some(_), pat, .. }) = node { - return Some((pat.span, "expected because of this assignment".to_string())); + let span = self.tcx.hir().span(pat.hir_id); + return Some((span, "expected because of this assignment".to_string())); } None } @@ -539,11 +540,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Some(expr) = &block.expr { (expr.span, None) } else if let Some(stmt) = block.stmts.last() { + let span = self.tcx.hir().span(stmt.hir_id); // possibly incorrect trailing `;` in the else arm - (stmt.span, expected_ty.and_then(|ty| self.could_remove_semicolon(block, ty))) + (span, expected_ty.and_then(|ty| self.could_remove_semicolon(block, ty))) } else { // empty block; point at its entirety - (block.span, None) + let block_span = self.tcx.hir().span(block.hir_id); + (block_span, None) } } } diff --git a/compiler/rustc_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index 9c60e8933d4db..e1a2178fddf35 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -143,7 +143,7 @@ pub(super) fn check_fn<'a, 'tcx>( // C-variadic fns also have a `VaList` input that's not listed in `fn_sig` // (as it's created inside the body itself, not passed in from outside). let maybe_va_list = if fn_sig.c_variadic { - let span = body.params.last().unwrap().span; + let span = tcx.hir().span(body.params.last().unwrap().hir_id); let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span)); let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span)); @@ -165,7 +165,8 @@ pub(super) fn check_fn<'a, 'tcx>( // for simple cases like `fn foo(x: Trait)`, // where we would error once on the parameter as a whole, and once on the binding `x`. if param.pat.simple_ident().is_none() && !tcx.features().unsized_fn_params { - fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType(ty_span)); + let pat_span = tcx.hir().span(param.pat.hir_id); + fcx.require_type_is_sized(param_ty, pat_span, traits::SizedArgumentType(ty_span)); } fcx.write_ty(param.hir_id, param_ty); @@ -775,14 +776,15 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { (0, _) => ("const", "consts", None), _ => ("type or const", "types or consts", None), }; + let item_span = tcx.hir().span(item.id.hir_id); struct_span_err!( tcx.sess, - item.span, + item_span, E0044, "foreign items may not have {} parameters", kinds, ) - .span_label(item.span, &format!("can't have {} parameters", kinds)) + .span_label(item_span, &format!("can't have {} parameters", kinds)) .help( // FIXME: once we start storing spans for type arguments, turn this // into a suggestion. @@ -1345,10 +1347,10 @@ pub fn check_enum<'tcx>( Some(ref expr) => tcx.hir().span(expr.hir_id), None => tcx.hir().span(variant_i_hir_id), }; - let span = match v.disr_expr { - Some(ref expr) => tcx.hir().span(expr.hir_id), - None => v.span, - }; + let span = tcx.hir().span(match v.disr_expr { + Some(ref expr) => expr.hir_id, + None => v.id, + }); struct_span_err!( tcx.sess, span, diff --git a/compiler/rustc_typeck/src/check/compare_method.rs b/compiler/rustc_typeck/src/check/compare_method.rs index bb324d0d8bc1e..c94e48a9c8cfb 100644 --- a/compiler/rustc_typeck/src/check/compare_method.rs +++ b/compiler/rustc_typeck/src/check/compare_method.rs @@ -586,8 +586,12 @@ fn compare_number_of_generics<'tcx>( if trait_item.generics.params.is_empty() { (Some(vec![trait_item.generics.span]), vec![]) } else { - let arg_spans: Vec = - trait_item.generics.params.iter().map(|p| p.span).collect(); + let arg_spans: Vec = trait_item + .generics + .params + .iter() + .map(|p| tcx.hir().span(p.hir_id)) + .collect(); let impl_trait_spans: Vec = trait_item .generics .params @@ -596,7 +600,7 @@ fn compare_number_of_generics<'tcx>( GenericParamKind::Type { synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), .. - } => Some(p.span), + } => Some(tcx.hir().span(p.hir_id)), _ => None, }) .collect(); @@ -616,11 +620,21 @@ fn compare_number_of_generics<'tcx>( GenericParamKind::Type { synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), .. - } => Some(p.span), + } => Some(tcx.hir().span(p.hir_id)), _ => None, }) .collect(); - let spans = impl_item.generics.spans(); + let spans: rustc_span::MultiSpan = if impl_item.generics.params.is_empty() { + impl_item.generics.span.into() + } else { + impl_item + .generics + .params + .iter() + .map(|p| tcx.hir().span(p.hir_id)) + .collect::>() + .into() + }; let span = spans.primary_span(); let mut err = tcx.sess.struct_span_err_with_code( diff --git a/compiler/rustc_typeck/src/check/expr.rs b/compiler/rustc_typeck/src/check/expr.rs index d76a80d5a3990..378c5f429396a 100644 --- a/compiler/rustc_typeck/src/check/expr.rs +++ b/compiler/rustc_typeck/src/check/expr.rs @@ -827,7 +827,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let coerce = match source { // you can only use break with a value from a normal `loop { }` hir::LoopSource::Loop => { - let coerce_to = expected.coercion_target_type(self, body.span); + let span = self.tcx.hir().span(body.hir_id); + let coerce_to = expected.coercion_target_type(self, span); Some(CoerceMany::new(coerce_to)) } @@ -855,8 +856,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // (which would have type !) are only possible iff we // permit break with a value [1]. if ctxt.coerce.is_none() && !ctxt.may_break { + let span = self.tcx.hir().span(body.hir_id); // [1] - self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break"); + self.tcx.sess.delay_span_bug(span, "no coercion, but loop may not break"); } ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit()) } @@ -1202,17 +1204,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for field in ast_fields { let ident = tcx.adjust_ident(field.ident, variant.def_id); let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) { - seen_fields.insert(ident, field.span); + let field_span = self.tcx.hir().span(field.hir_id); + seen_fields.insert(ident, field_span); self.write_field_index(field.hir_id, i); // We don't look at stability attributes on // struct-like enums (yet...), but it's definitely not // a bug to have constructed one. if adt_kind != AdtKind::Enum { - tcx.check_stability(v_field.did, Some(expr_id), field.span); + tcx.check_stability(v_field.did, Some(expr_id), field_span); } - self.field_ty(field.span, v_field, substs) + self.field_ty(field_span, v_field, substs) } else { error_happened = true; if let Some(prev_span) = seen_fields.get(&ident) { diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs index 7126b62405968..7c1dc89642c11 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs @@ -1120,7 +1120,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { return None; } - let original_span = original_sp(last_stmt.span, blk.span); + let last_stmt_span = self.tcx.hir().span(last_stmt.hir_id); + let blk_span = self.tcx.hir().span(blk.hir_id); + let original_span = original_sp(last_stmt_span, blk_span); Some((original_span.with_lo(original_span.hi() - BytePos(1)), needs_box)) } diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs index 3e60924d6fcf8..19ad18fe64f48 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs @@ -129,10 +129,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .and_then(|args| args.args.iter().last()) // Account for `foo.bar::()`. .map(|arg| { + let arg_span = tcx.hir().span(arg.id()); // Skip the closing `>`. tcx.sess .source_map() - .next_point(tcx.sess.source_map().next_point(arg.span())) + .next_point(tcx.sess.source_map().next_point(arg_span)) }) .unwrap_or(*span), &args[1..], // Skip the receiver. @@ -183,7 +184,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Some(id) = node.body_id() { let body = tcx.hir().body(id); for param in body.params { - spans.push_span_label(param.span, String::new()); + let param_span = tcx.hir().span(param.hir_id); + spans.push_span_label(param_span, String::new()); } } @@ -513,7 +515,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Type check a `let` statement. pub fn check_decl_local(&self, local: &'tcx hir::Local<'tcx>) { // Determine and write the type which we'll check the pattern against. - let ty = self.local_ty(local.span, local.hir_id).decl_ty; + let local_span = self.tcx().hir().span(local.hir_id); + let ty = self.local_ty(local_span, local.hir_id).decl_ty; self.write_ty(local.hir_id, ty); // Type check the initializer. @@ -542,7 +545,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir::StmtKind::Local(..) | hir::StmtKind::Expr(..) | hir::StmtKind::Semi(..) => {} } - self.warn_if_unreachable(stmt.hir_id, stmt.span, "statement"); + let stmt_span = self.tcx.hir().span(stmt.hir_id); + self.warn_if_unreachable(stmt.hir_id, stmt_span, "statement"); // Hide the outer diverging and `has_errors` flags. let old_diverges = self.diverges.replace(Diverges::Maybe); @@ -577,7 +581,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // if the block produces a `!` value, that can always be // (effectively) coerced to unit. if !ty.is_never() { - self.demand_suptype(blk.span, unit, ty); + let blk_span = self.tcx.hir().span(blk.hir_id); + self.demand_suptype(blk_span, unit, ty); } } @@ -609,7 +614,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // break 'a 22; }` would not force the type of the block // to be `()`). let tail_expr = blk.expr.as_ref(); - let coerce_to_ty = expected.coercion_target_type(self, blk.span); + let blk_span = self.tcx.hir().span(blk.hir_id); + let coerce_to_ty = expected.coercion_target_type(self, blk_span); let coerce = if blk.targeted_by_break { CoerceMany::new(coerce_to_ty) } else { @@ -657,7 +663,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // `consider_hint_about_removing_semicolon` will point at the last expression // if it were a relevant part of the error. This improves usability in editors // that highlight errors inline. - let mut sp = blk.span; + let mut sp = self.tcx.hir().span(blk.hir_id); let mut fn_span = None; if let Some((decl, ident)) = self.get_parent_fn_decl(blk.hir_id) { let ret_sp = decl.output.span(); @@ -665,7 +671,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // HACK: on some cases (`ui/liveness/liveness-issue-2163.rs`) the // output would otherwise be incorrect and even misleading. Make sure // the span we're aiming at correspond to a `fn` body. - if block_sp == blk.span { + let blk_span = self.tcx.hir().span(blk.hir_id); + if block_sp == blk_span { sp = ret_sp; fn_span = Some(ident.span); } @@ -781,7 +788,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body_id), .. }) => { let body = self.tcx.hir().body(body_id); if let ExprKind::Block(block, _) = &body.value.kind { - return Some(block.span); + let block_span = self.tcx.hir().span(block.hir_id); + return Some(block_span); } } _ => {} @@ -818,7 +826,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Some(match &arm.body.kind { // Point at the tail expression when possible. hir::ExprKind::Block(block, _) => { - block.expr.as_ref().map(|e| e.span).unwrap_or(block.span) + let block_span = self.tcx.hir().span(block.hir_id); + block.expr.as_ref().map(|e| e.span).unwrap_or(block_span) } _ => arm.body.span, }) diff --git a/compiler/rustc_typeck/src/check/gather_locals.rs b/compiler/rustc_typeck/src/check/gather_locals.rs index 825ebc19fa6da..f00ddde4d6e40 100644 --- a/compiler/rustc_typeck/src/check/gather_locals.rs +++ b/compiler/rustc_typeck/src/check/gather_locals.rs @@ -80,7 +80,8 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> { } None => None, }; - self.assign(local.span, local.hir_id, local_ty); + let local_span = self.fcx.tcx.hir().span(local.hir_id); + self.assign(local_span, local.hir_id, local_ty); debug!( "local variable {:?} is assigned type {}", @@ -99,19 +100,20 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> { // Add pattern bindings. fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { if let PatKind::Binding(_, _, ident, _) = p.kind { - let var_ty = self.assign(p.span, p.hir_id, None); + let span = self.fcx.tcx.hir().span(p.hir_id); + let var_ty = self.assign(span, p.hir_id, None); if self.outermost_fn_param_pat { if !self.fcx.tcx.features().unsized_fn_params { self.fcx.require_type_is_sized( var_ty, - p.span, - traits::SizedArgumentType(Some(p.span)), + span, + traits::SizedArgumentType(Some(span)), ); } } else { if !self.fcx.tcx.features().unsized_locals { - self.fcx.require_type_is_sized(var_ty, p.span, traits::VariableType(p.hir_id)); + self.fcx.require_type_is_sized(var_ty, span, traits::VariableType(p.hir_id)); } } @@ -133,7 +135,6 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> { _: intravisit::FnKind<'tcx>, _: &'tcx hir::FnDecl<'tcx>, _: hir::BodyId, - _: Span, _: hir::HirId, ) { } diff --git a/compiler/rustc_typeck/src/check/generator_interior.rs b/compiler/rustc_typeck/src/check/generator_interior.rs index 91708465b3f60..ca971bef6a8a0 100644 --- a/compiler/rustc_typeck/src/check/generator_interior.rs +++ b/compiler/rustc_typeck/src/check/generator_interior.rs @@ -271,7 +271,8 @@ impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> { if let PatKind::Binding(..) = pat.kind { let scope = self.region_scope_tree.var_scope(pat.hir_id.local_id); let ty = self.fcx.typeck_results.borrow().pat_ty(pat); - self.record(ty, Some(scope), None, pat.span, false); + let span = self.fcx.tcx.hir().span(pat.hir_id); + self.record(ty, Some(scope), None, span, false); } } diff --git a/compiler/rustc_typeck/src/check/method/suggest.rs b/compiler/rustc_typeck/src/check/method/suggest.rs index 5cfd78ebeacad..12e09f1f07fe7 100644 --- a/compiler/rustc_typeck/src/check/method/suggest.rs +++ b/compiler/rustc_typeck/src/check/method/suggest.rs @@ -1425,7 +1425,7 @@ impl UsePlacementFinder<'tcx> { } impl intravisit::Visitor<'tcx> for UsePlacementFinder<'tcx> { - fn visit_mod(&mut self, module: &'tcx hir::Mod<'tcx>, _: Span, hir_id: hir::HirId) { + fn visit_mod(&mut self, module: &'tcx hir::Mod<'tcx>, hir_id: hir::HirId) { if self.span.is_some() { return; } diff --git a/compiler/rustc_typeck/src/check/mod.rs b/compiler/rustc_typeck/src/check/mod.rs index 8177b363a5a5b..954032210affd 100644 --- a/compiler/rustc_typeck/src/check/mod.rs +++ b/compiler/rustc_typeck/src/check/mod.rs @@ -699,7 +699,8 @@ fn binding_opaque_type_cycle_error( source: hir::LocalSource::Normal, .. }) => { - err.span_label(pat.span, "this binding might not have a concrete type"); + let pat_span = tcx.hir().span(pat.hir_id); + err.span_label(pat_span, "this binding might not have a concrete type"); err.span_suggestion_verbose( ty.span.shrink_to_hi(), "set the binding to a value for a concrete type to be resolved", diff --git a/compiler/rustc_typeck/src/check/pat.rs b/compiler/rustc_typeck/src/check/pat.rs index 5fc573a57ad0b..a61a46f892e8d 100644 --- a/compiler/rustc_typeck/src/check/pat.rs +++ b/compiler/rustc_typeck/src/check/pat.rs @@ -157,8 +157,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { def_bm: BindingMode, ti: TopInfo<'tcx>, ) { + let pat_span = self.tcx.hir().span(pat.hir_id); let path_res = match &pat.kind { - PatKind::Path(qpath) => Some(self.resolve_ty_and_res_ufcs(qpath, pat.hir_id, pat.span)), + PatKind::Path(qpath) => Some(self.resolve_ty_and_res_ufcs(qpath, pat.hir_id, pat_span)), _ => None, }; let adjust_mode = self.calc_adjust_mode(pat, path_res.map(|(res, ..)| res)); @@ -166,8 +167,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ty = match pat.kind { PatKind::Wild => expected, - PatKind::Lit(lt) => self.check_pat_lit(pat.span, lt, expected, ti), - PatKind::Range(lhs, rhs, _) => self.check_pat_range(pat.span, lhs, rhs, expected, ti), + PatKind::Lit(lt) => self.check_pat_lit(pat_span, lt, expected, ti), + PatKind::Range(lhs, rhs, _) => self.check_pat_range(pat_span, lhs, rhs, expected, ti), PatKind::Binding(ba, var_id, _, sub) => { self.check_pat_ident(pat, ba, var_id, sub, expected, def_bm, ti) } @@ -186,14 +187,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected } PatKind::Tuple(elements, ddpos) => { - self.check_pat_tuple(pat.span, elements, ddpos, expected, def_bm, ti) + self.check_pat_tuple(pat_span, elements, ddpos, expected, def_bm, ti) } - PatKind::Box(inner) => self.check_pat_box(pat.span, inner, expected, def_bm, ti), + PatKind::Box(inner) => self.check_pat_box(pat_span, inner, expected, def_bm, ti), PatKind::Ref(inner, mutbl) => { self.check_pat_ref(pat, inner, mutbl, expected, def_bm, ti) } PatKind::Slice(before, slice, after) => { - self.check_pat_slice(pat.span, before, slice, after, expected, def_bm, ti) + self.check_pat_slice(pat_span, before, slice, after, expected, def_bm, ti) } }; @@ -554,7 +555,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!("check_pat_ident: pat.hir_id={:?} bm={:?}", pat.hir_id, bm); - let local_ty = self.local_ty(pat.span, pat.hir_id).decl_ty; + let pat_span = self.tcx.hir().span(pat.hir_id); + let local_ty = self.local_ty(pat_span, pat.hir_id).decl_ty; let eq_ty = match bm { ty::BindByReference(mutbl) => { // If the binding is like `ref x | ref mut x`, @@ -564,7 +566,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // `x` is assigned a value of type `&M T`, hence `&M T <: typeof(x)` // is required. However, we use equality, which is stronger. // See (note_1) for an explanation. - self.new_ref_ty(pat.span, mutbl, expected) + self.new_ref_ty(pat_span, mutbl, expected) } // Otherwise, the type of x is the expected type `T`. ty::BindByValue(_) => { @@ -572,12 +574,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected } }; - self.demand_eqtype_pat(pat.span, eq_ty, local_ty, ti); + self.demand_eqtype_pat(pat_span, eq_ty, local_ty, ti); // If there are multiple arms, make sure they all agree on // what the type of the binding `x` ought to be. if var_id != pat.hir_id { - self.check_binding_alt_eq_ty(pat.span, var_id, local_ty, ti); + self.check_binding_alt_eq_ty(pat_span, var_id, local_ty, ti); } if let Some(p) = sub { @@ -622,10 +624,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let binding_parent = tcx.hir().get(binding_parent_id); debug!("inner {:?} pat {:?} parent {:?}", inner, pat, binding_parent); match binding_parent { - hir::Node::Param(hir::Param { span, .. }) => { - if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner.span) { + hir::Node::Param(hir::Param { hir_id, .. }) => { + let span = tcx.hir().span(*hir_id); + let inner_span = self.tcx.hir().span(inner.hir_id); + if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner_span) { err.span_suggestion( - *span, + span, &format!("did you mean `{}`", snippet), format!(" &{}", expected), Applicability::MachineApplicable, @@ -634,9 +638,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } hir::Node::Arm(_) | hir::Node::Pat(_) => { // rely on match ergonomics or it might be nested `&&pat` - if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner.span) { + let inner_span = self.tcx.hir().span(inner.hir_id); + if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner_span) { + let pat_span = self.tcx.hir().span(pat.hir_id); err.span_suggestion( - pat.span, + pat_span, "you can probably remove the explicit borrow", snippet, Applicability::MaybeIncorrect, @@ -698,7 +704,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // Type-check the path. - self.demand_eqtype_pat(pat.span, expected, pat_ty, ti); + let pat_span = self.tcx.hir().span(pat.hir_id); + self.demand_eqtype_pat(pat_span, expected, pat_ty, ti); // Type-check subpatterns. if self.check_struct_pat_fields(pat_ty, &pat, variant, fields, etc, def_bm, ti) { @@ -725,7 +732,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return tcx.ty_error(); } Res::Def(DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fictive | CtorKind::Fn), _) => { - report_unexpected_variant_res(tcx, res, pat.span); + let pat_span = self.tcx.hir().span(pat.hir_id); + report_unexpected_variant_res(tcx, res, pat_span); return tcx.ty_error(); } Res::SelfCtor(..) @@ -740,12 +748,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } // Type-check the path. + let pat_span = self.tcx.hir().span(pat.hir_id); let (pat_ty, pat_res) = - self.instantiate_value_path(segments, opt_ty, res, pat.span, pat.hir_id); + self.instantiate_value_path(segments, opt_ty, res, pat_span, pat.hir_id); if let Some(err) = - self.demand_suptype_with_origin(&self.pattern_cause(ti, pat.span), expected, pat_ty) + self.demand_suptype_with_origin(&self.pattern_cause(ti, pat_span), expected, pat_ty) { - self.emit_bad_pat_path(err, pat.span, res, pat_res, pat_ty, segments, ti.parent_pat); + self.emit_bad_pat_path(err, pat_span, res, pat_res, pat_ty, segments, ti.parent_pat); } pat_ty } @@ -873,10 +882,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.check_pat(&pat, tcx.ty_error(), def_bm, TopInfo { parent_pat, ..ti }); } }; + let pat_span = self.tcx.hir().span(pat.hir_id); let report_unexpected_res = |res: Res| { let sm = tcx.sess.source_map(); let path_str = sm - .span_to_snippet(sm.span_until_char(pat.span, '(')) + .span_to_snippet(sm.span_until_char(pat_span, '(')) .map_or(String::new(), |s| format!(" `{}`", s.trim_end())); let msg = format!( "expected tuple struct or tuple variant, found {}{}", @@ -884,17 +894,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { path_str ); - let mut err = struct_span_err!(tcx.sess, pat.span, E0164, "{}", msg); + let mut err = struct_span_err!(tcx.sess, pat_span, E0164, "{}", msg); match res { Res::Def(DefKind::Fn | DefKind::AssocFn, _) => { - err.span_label(pat.span, "`fn` calls are not allowed in patterns"); + err.span_label(pat_span, "`fn` calls are not allowed in patterns"); err.help( "for more information, visit \ https://doc.rust-lang.org/book/ch18-00-patterns.html", ); } _ => { - err.span_label(pat.span, "not a tuple variant or struct"); + err.span_label(pat_span, "not a tuple variant or struct"); } } err.emit(); @@ -902,7 +912,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // Resolve the path and check the definition for errors. - let (res, opt_ty, segments) = self.resolve_ty_and_res_ufcs(qpath, pat.hir_id, pat.span); + let (res, opt_ty, segments) = self.resolve_ty_and_res_ufcs(qpath, pat.hir_id, pat_span); if res == Res::Err { self.set_tainted_by_errors(); on_error(); @@ -911,7 +921,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Type-check the path. let (pat_ty, res) = - self.instantiate_value_path(segments, opt_ty, res, pat.span, pat.hir_id); + self.instantiate_value_path(segments, opt_ty, res, pat_span, pat.hir_id); if !pat_ty.is_fn() { report_unexpected_res(res); return tcx.ty_error(); @@ -936,7 +946,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let pat_ty = pat_ty.no_bound_vars().expect("expected fn type"); // Type-check the tuple struct pattern against the expected type. - let diag = self.demand_eqtype_pat_diag(pat.span, expected, pat_ty, ti); + let diag = self.demand_eqtype_pat_diag(pat_span, expected, pat_ty, ti); let had_err = if let Some(mut err) = diag { err.emit(); true @@ -953,14 +963,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => bug!("unexpected pattern type {:?}", pat_ty), }; for (i, subpat) in subpats.iter().enumerate_and_adjust(variant.fields.len(), ddpos) { - let field_ty = self.field_ty(subpat.span, &variant.fields[i], substs); + let subpat_span = self.tcx.hir().span(subpat.hir_id); + let field_ty = self.field_ty(subpat_span, &variant.fields[i], substs); self.check_pat(&subpat, field_ty, def_bm, TopInfo { parent_pat: Some(&pat), ..ti }); - self.tcx.check_stability(variant.fields[i].did, Some(pat.hir_id), subpat.span); + self.tcx.check_stability(variant.fields[i].did, Some(pat.hir_id), subpat_span); } } else { // Pattern has wrong number of fields. - self.e0023(pat.span, res, qpath, subpats, &variant.fields, expected, had_err); + self.e0023(pat_span, res, qpath, subpats, &variant.fields, expected, had_err); on_error(); return tcx.ty_error(); } @@ -1033,7 +1044,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // | // L | let A((x, y)) = A((1, 2)); // | ^ ^ - [first, ..] => (first.span.shrink_to_lo(), subpats.last().unwrap().span), + [first, ..] => ( + self.tcx.hir().span(first.hir_id).shrink_to_lo(), + self.tcx.hir().span(subpats.last().unwrap().hir_id), + ), }; err.multipart_suggestion( "missing parenthesis", @@ -1102,9 +1116,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> bool { let tcx = self.tcx; + let pat_span = self.tcx.hir().span(pat.hir_id); let (substs, adt) = match adt_ty.kind() { ty::Adt(adt, substs) => (substs, adt), - _ => span_bug!(pat.span, "struct pattern is not an ADT"), + _ => span_bug!(pat_span, "struct pattern is not an ADT"), }; // Index the struct fields' types. @@ -1122,7 +1137,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut inexistent_fields = vec![]; // Typecheck each field. for field in fields { - let span = field.span; + let span = tcx.hir().span(field.hir_id); let ident = tcx.adjust_ident(field.ident, variant.def_id); let field_ty = match used_fields.entry(ident) { Occupied(occupied) => { @@ -1178,11 +1193,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if adt.is_union() { if fields.len() != 1 { tcx.sess - .struct_span_err(pat.span, "union patterns should have exactly one field") + .struct_span_err(pat_span, "union patterns should have exactly one field") .emit(); } if etc { - tcx.sess.struct_span_err(pat.span, "`..` cannot be used in union patterns").emit(); + tcx.sess.struct_span_err(pat_span, "`..` cannot be used in union patterns").emit(); } } else if !etc && !unmentioned_fields.is_empty() { let no_accessible_unmentioned_fields = !unmentioned_fields.iter().any(|(field, _)| { @@ -1220,13 +1235,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn error_foreign_non_exhaustive_spat(&self, pat: &Pat<'_>, descr: &str, no_fields: bool) { let sess = self.tcx.sess; let sm = sess.source_map(); - let sp_brace = sm.end_point(pat.span); - let sp_comma = sm.end_point(pat.span.with_hi(sp_brace.hi())); + let pat_span = self.tcx.hir().span(pat.hir_id); + let sp_brace = sm.end_point(pat_span); + let sp_comma = sm.end_point(pat_span.with_hi(sp_brace.hi())); let sugg = if no_fields || sp_brace != sp_comma { ".. }" } else { ", .. }" }; let mut err = struct_span_err!( sess, - pat.span, + pat_span, E0638, "`..` required with {} marked as non-exhaustive", descr @@ -1347,9 +1363,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let path = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| { s.print_qpath(qpath, false) }); + let pat_span = self.tcx.hir().span(pat.hir_id); let mut err = struct_span_err!( self.tcx.sess, - pat.span, + pat_span, E0769, "tuple variant `{}` written as struct variant", path @@ -1358,11 +1375,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ( fields .iter() - .map(|f| match self.tcx.sess.source_map().span_to_snippet(f.pat.span) { - Ok(f) => f, - Err(_) => rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| { - s.print_pat(f.pat) - }), + .map(|f| { + match self + .tcx + .sess + .source_map() + .span_to_snippet(self.tcx.hir().span(f.pat.hir_id)) + { + Ok(f) => f, + Err(_) => { + rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| { + s.print_pat(f.pat) + }) + } + } }) .collect::>() .join(", "), @@ -1375,7 +1401,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) }; err.span_suggestion( - pat.span, + pat_span, "use the tuple variant pattern syntax instead", format!("{}({})", path, sugg), appl, @@ -1405,14 +1431,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pat: &Pat<'_>, fields: &'tcx [hir::FieldPat<'tcx>], ) -> DiagnosticBuilder<'tcx> { + let pat_span = self.tcx.hir().span(pat.hir_id); let mut err = self .tcx .sess - .struct_span_err(pat.span, "pattern requires `..` due to inaccessible fields"); + .struct_span_err(pat_span, "pattern requires `..` due to inaccessible fields"); if let Some(field) = fields.last() { + let field_span = self.tcx.hir().span(field.hir_id); err.span_suggestion_verbose( - field.span.shrink_to_hi(), + field_span.shrink_to_hi(), "ignore the inaccessible and unused fields", ", ..".to_string(), Applicability::MachineApplicable, @@ -1425,7 +1453,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // Shrink the span to exclude the `foo:Foo` in `foo::Foo { }`. - let span = pat.span.with_lo(qpath_span.shrink_to_hi().hi()); + let span = pat_span.with_lo(qpath_span.shrink_to_hi().hi()); err.span_suggestion_verbose( span, "ignore the inaccessible and unused fields", @@ -1461,30 +1489,31 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .join(", "); format!("fields {}", fields) }; + let pat_span = self.tcx.hir().span(pat.hir_id); let mut err = struct_span_err!( self.tcx.sess, - pat.span, + pat_span, E0027, "pattern does not mention {}", field_names ); - err.span_label(pat.span, format!("missing {}", field_names)); + err.span_label(pat_span, format!("missing {}", field_names)); let len = unmentioned_fields.len(); let (prefix, postfix, sp) = match fields { [] => match &pat.kind { PatKind::Struct(path, [], false) => { - (" { ", " }", path.span().shrink_to_hi().until(pat.span.shrink_to_hi())) + (" { ", " }", path.span().shrink_to_hi().until(pat_span.shrink_to_hi())) } _ => return err, }, - [.., field] => ( - match pat.kind { + [.., field] => { + let field_span = self.tcx.hir().span(field.hir_id); + let prefix = match pat.kind { PatKind::Struct(_, [_, ..], _) => ", ", _ => "", - }, - "", - field.span.shrink_to_hi(), - ), + }; + (prefix, "", field_span.shrink_to_hi()) + } }; err.span_suggestion( sp, @@ -1530,9 +1559,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (box_ty, inner_ty) = if self.check_dereferenceable(span, expected, &inner) { // Here, `demand::subtype` is good enough, but I don't // think any errors can be introduced by using `demand::eqtype`. + let inner_span = tcx.hir().span(inner.hir_id); let inner_ty = self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, - span: inner.span, + span: inner_span, }); let box_ty = tcx.mk_box(inner_ty); self.demand_eqtype_pat(span, expected, box_ty, ti); @@ -1556,7 +1586,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> Ty<'tcx> { let tcx = self.tcx; let expected = self.shallow_resolve(expected); - let (rptr_ty, inner_ty) = if self.check_dereferenceable(pat.span, expected, &inner) { + let pat_span = self.tcx.hir().span(pat.hir_id); + let (rptr_ty, inner_ty) = if self.check_dereferenceable(pat_span, expected, &inner) { // `demand::subtype` would be good enough, but using `eqtype` turns // out to be equally general. See (note_1) for details. @@ -1567,13 +1598,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match *expected.kind() { ty::Ref(_, r_ty, r_mutbl) if r_mutbl == mutbl => (expected, r_ty), _ => { + let inner_span = tcx.hir().span(inner.hir_id); let inner_ty = self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, - span: inner.span, + span: inner_span, }); - let rptr_ty = self.new_ref_ty(pat.span, mutbl, inner_ty); + let rptr_ty = self.new_ref_ty(pat_span, mutbl, inner_ty); debug!("check_pat_ref: demanding {:?} = {:?}", expected, rptr_ty); - let err = self.demand_eqtype_pat_diag(pat.span, expected, rptr_ty, ti); + let err = self.demand_eqtype_pat_diag(pat_span, expected, rptr_ty, ti); // Look for a case like `fn foo(&foo: u32)` and suggest // `fn foo(foo: &u32)` diff --git a/compiler/rustc_typeck/src/check/regionck.rs b/compiler/rustc_typeck/src/check/regionck.rs index 88e8dd3cb129a..da56e05ba0f48 100644 --- a/compiler/rustc_typeck/src/check/regionck.rs +++ b/compiler/rustc_typeck/src/check/regionck.rs @@ -322,7 +322,8 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat<'_>) { debug!("regionck::visit_pat(pat={:?})", pat); - pat.each_binding(|_, hir_id, span, _| { + pat.each_binding(|_, hir_id, _| { + let span = self.tcx.hir().span(hir_id); let typ = self.resolve_node_type(hir_id); let body_id = self.body_id; dropck::check_drop_obligations(self, typ, span, body_id); @@ -350,7 +351,6 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> { fk: intravisit::FnKind<'tcx>, _: &'tcx hir::FnDecl<'tcx>, body_id: hir::BodyId, - span: Span, hir_id: hir::HirId, ) { assert!( @@ -365,6 +365,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> { let env_snapshot = self.outlives_environment.push_snapshot_pre_closure(); let body = self.tcx.hir().body(body_id); + let span = self.tcx.hir().span(hir_id); self.visit_fn_body(hir_id, body, span); // Restore state from previous function. @@ -562,8 +563,8 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { fn link_fn_params(&self, params: &[hir::Param<'_>]) { for param in params { let param_ty = self.node_ty(param.hir_id); - let param_cmt = - self.with_mc(|mc| mc.cat_rvalue(param.hir_id, param.pat.span, param_ty)); + let span = self.tcx.hir().span(param.pat.hir_id); + let param_cmt = self.with_mc(|mc| mc.cat_rvalue(param.hir_id, span, param_ty)); debug!("param_ty={:?} param_cmt={:?} param={:?}", param_ty, param_cmt, param); self.link_pattern(param_cmt, ¶m.pat); } @@ -574,13 +575,14 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { fn link_pattern(&self, discr_cmt: PlaceWithHirId<'tcx>, root_pat: &hir::Pat<'_>) { debug!("link_pattern(discr_cmt={:?}, root_pat={:?})", discr_cmt, root_pat); ignore_err!(self.with_mc(|mc| { - mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, hir::Pat { kind, span, hir_id, .. }| { + mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, hir::Pat { kind, hir_id, .. }| { // `ref x` pattern if let PatKind::Binding(..) = kind { + let span = self.tcx.hir().span(*hir_id); if let Some(ty::BindByReference(mutbl)) = - mc.typeck_results.extract_binding_mode(self.tcx.sess, *hir_id, *span) + mc.typeck_results.extract_binding_mode(self.tcx.sess, *hir_id, span) { - self.link_region_from_node_type(*span, *hir_id, mutbl, &sub_cmt); + self.link_region_from_node_type(span, *hir_id, mutbl, &sub_cmt); } } }) diff --git a/compiler/rustc_typeck/src/check/wfcheck.rs b/compiler/rustc_typeck/src/check/wfcheck.rs index d81d83f60bd13..49a1f5736f8fc 100644 --- a/compiler/rustc_typeck/src/check/wfcheck.rs +++ b/compiler/rustc_typeck/src/check/wfcheck.rs @@ -290,6 +290,7 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) { // FIXME(const_generics_defaults): we also need to check that the `default` is wf. hir::GenericParamKind::Const { ty: hir_ty, default: _ } => { let ty = tcx.type_of(tcx.hir().local_def_id(param.hir_id)); + let param_span = tcx.hir().span(param.hir_id); let err_ty_str; let mut is_ptr = true; @@ -335,7 +336,7 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) { } }; - if traits::search_for_structural_match_violation(param.hir_id, param.span, tcx, ty) + if traits::search_for_structural_match_violation(param.hir_id, param_span, tcx, ty) .is_some() { // We use the same error code in both branches, because this is really the same @@ -1273,7 +1274,7 @@ fn check_variances_for_type_defn<'tcx>( match param.name { hir::ParamName::Error => {} - _ => report_bivariance(tcx, param.span, param.name.ident().name), + _ => report_bivariance(tcx, tcx.hir().span(param.hir_id), param.name.ident().name), } } } diff --git a/compiler/rustc_typeck/src/check/writeback.rs b/compiler/rustc_typeck/src/check/writeback.rs index 7c9cfe69fc94b..105847155c975 100644 --- a/compiler/rustc_typeck/src/check/writeback.rs +++ b/compiler/rustc_typeck/src/check/writeback.rs @@ -45,7 +45,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_substs); for param in body.params { - wbcx.visit_node_id(param.pat.span, param.hir_id); + let span = self.tcx.hir().span(param.pat.hir_id); + wbcx.visit_node_id(span, param.hir_id); } // Type only exists for constants and statics, not functions. match self.tcx.hir().body_owner_kind(item_id) { @@ -288,16 +289,18 @@ impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { } fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) { - self.visit_node_id(b.span, b.hir_id); + let span = self.tcx().hir().span(b.hir_id); + self.visit_node_id(span, b.hir_id); intravisit::walk_block(self, b); } fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { + let span = self.tcx().hir().span(p.hir_id); match p.kind { hir::PatKind::Binding(..) => { let typeck_results = self.fcx.typeck_results.borrow(); if let Some(bm) = - typeck_results.extract_binding_mode(self.tcx().sess, p.hir_id, p.span) + typeck_results.extract_binding_mode(self.tcx().sess, p.hir_id, span) { self.typeck_results.pat_binding_modes_mut().insert(p.hir_id, bm); } @@ -310,16 +313,17 @@ impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { _ => {} }; - self.visit_pat_adjustments(p.span, p.hir_id); + self.visit_pat_adjustments(span, p.hir_id); - self.visit_node_id(p.span, p.hir_id); + self.visit_node_id(span, p.hir_id); intravisit::walk_pat(self, p); } fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { intravisit::walk_local(self, l); - let var_ty = self.fcx.local_ty(l.span, l.hir_id).decl_ty; - let var_ty = self.resolve(var_ty, &l.span); + let span = self.tcx().hir().span(l.hir_id); + let var_ty = self.fcx.local_ty(span, l.hir_id).decl_ty; + let var_ty = self.resolve(var_ty, &span); self.write_ty_to_typeck_results(l.hir_id, var_ty); } diff --git a/compiler/rustc_typeck/src/coherence/orphan.rs b/compiler/rustc_typeck/src/coherence/orphan.rs index 253dcf06e01de..db2ff0132d8bc 100644 --- a/compiler/rustc_typeck/src/coherence/orphan.rs +++ b/compiler/rustc_typeck/src/coherence/orphan.rs @@ -85,7 +85,7 @@ impl ItemLikeVisitor<'v> for OrphanChecker<'tcx> { let mut sp = sp; for param in generics.params { if param.name.ident().to_string() == param_ty.to_string() { - sp = param.span; + sp = self.tcx.hir().span(param.hir_id); } } diff --git a/compiler/rustc_typeck/src/collect.rs b/compiler/rustc_typeck/src/collect.rs index ae97fa3f7e423..075045d441005 100644 --- a/compiler/rustc_typeck/src/collect.rs +++ b/compiler/rustc_typeck/src/collect.rs @@ -162,12 +162,14 @@ crate fn placeholder_type_error( { // Account for `_` already present in cases like `struct S<_>(_);` and suggest // `struct S(T);` instead of `struct S<_, T>(T);`. - sugg.push((arg.span, (*type_name).to_string())); + let arg_span = tcx.hir().span(arg.hir_id); + sugg.push((arg_span, (*type_name).to_string())); } else { let last = generics.iter().last().unwrap(); + let last_span = tcx.hir().span(last.hir_id); sugg.push(( // Account for bounds, we want `fn foo(_: K)` not `fn foo(_: K)`. - last.bounds_span().unwrap_or(last.span).shrink_to_hi(), + last.bounds_span().unwrap_or(last_span).shrink_to_hi(), format!(", {}", type_name), )); } @@ -375,7 +377,8 @@ impl AstConv<'tcx> for ItemCtxt<'tcx> { let (lt_sp, sugg) = match &generics.params[..] { [] => (generics.span, format!("<{}>", lt_name)), [bound, ..] => { - (bound.span.shrink_to_lo(), format!("{}, ", lt_name)) + let bound_span = self.tcx.hir().span(bound.hir_id); + (bound_span.shrink_to_lo(), format!("{}, ", lt_name)) } }; let suggestions = vec![ @@ -813,11 +816,9 @@ fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::V } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) { Some(discr) } else { - struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed") - .span_label( - variant.span, - format!("overflowed on value after {}", prev_discr.unwrap()), - ) + let span = tcx.hir().span(variant.id); + struct_span_err!(tcx.sess, span, E0370, "enum discriminant overflowed") + .span_label(span, format!("overflowed on value after {}", prev_discr.unwrap())) .note(&format!( "explicitly set `{} = {}` if that is desired outcome", variant.ident, wrapped_discr @@ -859,15 +860,16 @@ fn convert_variant( .iter() .map(|f| { let fid = tcx.hir().local_def_id(f.hir_id); + let span = tcx.hir().span(f.hir_id); let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned(); if let Some(prev_span) = dup_span { tcx.sess.emit_err(errors::FieldAlreadyDeclared { field_name: f.ident, - span: f.span, + span, prev_span, }); } else { - seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span); + seen_fields.insert(f.ident.normalize_to_macros_2_0(), span); } ty::FieldDef { did: fid.to_def_id(), ident: f.ident, vis: tcx.visibility(fid) } @@ -1145,7 +1147,8 @@ fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option, def_id: DefId) -> ty::Generics { GenericParamKind::Type { ref default, synthetic, .. } => { if !allow_defaults && default.is_some() { if !tcx.features().default_type_parameter_fallback { + let param_span = tcx.hir().span(param.hir_id); tcx.struct_span_lint_hir( lint::builtin::INVALID_TYPE_PARAM_DEFAULT, param.hir_id, - param.span, + param_span, |lint| { lint.build( "defaults for type parameters are only allowed in \ @@ -1904,8 +1908,8 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericP index += 1; let sized = SizedByDefault::Yes; - let bounds = - AstConv::compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span); + let span = tcx.hir().span(param.hir_id); + let bounds = AstConv::compute_bounds(&icx, param_ty, ¶m.bounds, sized, span); predicates.extend(bounds.predicates(tcx, param_ty)); } GenericParamKind::Const { .. } => { diff --git a/compiler/rustc_typeck/src/expr_use_visitor.rs b/compiler/rustc_typeck/src/expr_use_visitor.rs index 3ce244e11bf45..bb966855bef3d 100644 --- a/compiler/rustc_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_typeck/src/expr_use_visitor.rs @@ -122,7 +122,8 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { let param_ty = return_if_err!(self.mc.pat_ty_adjusted(¶m.pat)); debug!("consume_body: param_ty = {:?}", param_ty); - let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty); + let pat_span = self.tcx().hir().span(param.pat.hir_id); + let param_place = self.mc.cat_rvalue(param.hir_id, pat_span, param_ty); self.walk_irrefutable_pat(¶m_place, ¶m.pat); } @@ -534,8 +535,9 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| { if let PatKind::Binding(_, canonical_id, ..) = pat.kind { debug!("walk_pat: binding place={:?} pat={:?}", place, pat,); + let pat_span = tcx.hir().span(pat.hir_id); if let Some(bm) = - mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) + mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat_span) { debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm); @@ -546,7 +548,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { // Each match binding is effectively an assignment to the // binding being produced. let def = Res::Local(canonical_id); - if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) { + if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat_span, pat_ty, def) { delegate.mutate(binding_place, binding_place.hir_id); } diff --git a/compiler/rustc_typeck/src/mem_categorization.rs b/compiler/rustc_typeck/src/mem_categorization.rs index a601123c8d055..bbb1b952aab9f 100644 --- a/compiler/rustc_typeck/src/mem_categorization.rs +++ b/compiler/rustc_typeck/src/mem_categorization.rs @@ -67,25 +67,18 @@ use rustc_trait_selection::infer::InferCtxtExt; crate trait HirNode { fn hir_id(&self) -> hir::HirId; - fn span(&self) -> Span; } impl HirNode for hir::Expr<'_> { fn hir_id(&self) -> hir::HirId { self.hir_id } - fn span(&self) -> Span { - self.span - } } impl HirNode for hir::Pat<'_> { fn hir_id(&self) -> hir::HirId { self.hir_id } - fn span(&self) -> Span { - self.span - } } #[derive(Clone)] @@ -673,10 +666,11 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { // that (where the `ref` on `x` is implied). op(&place_with_id, pat); + let pat_span = self.infcx.tcx.hir().span(pat.hir_id); match pat.kind { PatKind::Tuple(ref subpats, dots_pos) => { // (p1, ..., pN) - let total_fields = self.total_fields_in_tuple(pat.hir_id, pat.span)?; + let total_fields = self.total_fields_in_tuple(pat.hir_id, pat_span)?; for (i, subpat) in subpats.iter().enumerate_and_adjust(total_fields, dots_pos) { let subpat_ty = self.pat_ty_adjusted(&subpat)?; @@ -689,9 +683,9 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { PatKind::TupleStruct(ref qpath, ref subpats, dots_pos) => { // S(p1, ..., pN) - let variant_index = self.variant_index_for_adt(qpath, pat.hir_id, pat.span)?; + let variant_index = self.variant_index_for_adt(qpath, pat.hir_id, pat_span)?; let total_fields = - self.total_fields_in_adt_variant(pat.hir_id, variant_index, pat.span)?; + self.total_fields_in_adt_variant(pat.hir_id, variant_index, pat_span)?; for (i, subpat) in subpats.iter().enumerate_and_adjust(total_fields, dots_pos) { let subpat_ty = self.pat_ty_adjusted(&subpat)?; @@ -705,7 +699,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { PatKind::Struct(ref qpath, field_pats, _) => { // S { f1: p1, ..., fN: pN } - let variant_index = self.variant_index_for_adt(qpath, pat.hir_id, pat.span)?; + let variant_index = self.variant_index_for_adt(qpath, pat.hir_id, pat_span)?; for fp in field_pats { let field_ty = self.pat_ty_adjusted(&fp.pat)?; diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 09627be9701c9..39e531b32cec1 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -136,7 +136,7 @@ crate fn run(options: Options) -> Result<(), ErrorReported> { "".to_string(), &krate.item.attrs, CRATE_HIR_ID, - krate.item.span, + tcx.hir().span(CRATE_HIR_ID), |this| { intravisit::walk_crate(this, krate); }, @@ -1061,13 +1061,14 @@ impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> g: &'hir hir::Generics<'_>, item_id: hir::HirId, ) { - self.visit_testable(v.ident.to_string(), &v.attrs, v.id, v.span, |this| { + self.visit_testable(v.ident.to_string(), &v.attrs, v.id, self.map.span(v.id), |this| { intravisit::walk_variant(this, v, g, item_id); }); } fn visit_struct_field(&mut self, f: &'hir hir::StructField<'_>) { - self.visit_testable(f.ident.to_string(), &f.attrs, f.hir_id, f.span, |this| { + let span = self.map.span(f.hir_id); + self.visit_testable(f.ident.to_string(), &f.attrs, f.hir_id, span, |this| { intravisit::walk_struct_field(this, f); }); } @@ -1077,7 +1078,7 @@ impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> macro_def.ident.to_string(), ¯o_def.attrs, macro_def.hir_id, - macro_def.span, + self.map.span(macro_def.hir_id), |_| (), ); } diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 3c0aeaad43e5d..778574c587003 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -62,7 +62,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { crate fn visit(mut self, krate: &'tcx hir::Crate<'_>) -> Module<'tcx> { let mut module = self.visit_mod_contents( - krate.item.span, + self.cx.tcx.hir().span(hir::CRATE_HIR_ID), &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public }, hir::CRATE_HIR_ID, &krate.item.module, diff --git a/src/test/ui-fulldeps/auxiliary/issue-40001-plugin.rs b/src/test/ui-fulldeps/auxiliary/issue-40001-plugin.rs index 4e9d4d342734c..82207ac5a3af4 100644 --- a/src/test/ui-fulldeps/auxiliary/issue-40001-plugin.rs +++ b/src/test/ui-fulldeps/auxiliary/issue-40001-plugin.rs @@ -40,7 +40,6 @@ impl<'tcx> LateLintPass<'tcx> for MissingAllowedAttrPass { _: intravisit::FnKind<'tcx>, _: &'tcx hir::FnDecl, _: &'tcx hir::Body, - span: source_map::Span, id: hir::HirId, ) { let item = match cx.tcx.hir().get(id) { @@ -51,6 +50,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingAllowedAttrPass { let allowed = |attr| pprust::attribute_to_string(attr).contains("allowed_attr"); if !item.attrs.iter().any(allowed) { cx.lint(MISSING_ALLOWED_ATTR, |lint| { + let span = cx.tcx.hir().span(id); lint.build("Missing 'allowed_attr' attribute").set_span(span).emit() }); } diff --git a/src/test/ui-fulldeps/auxiliary/lint-for-crate-rpass.rs b/src/test/ui-fulldeps/auxiliary/lint-for-crate-rpass.rs index 736a8633dac53..5507c81544804 100644 --- a/src/test/ui-fulldeps/auxiliary/lint-for-crate-rpass.rs +++ b/src/test/ui-fulldeps/auxiliary/lint-for-crate-rpass.rs @@ -31,8 +31,9 @@ macro_rules! fake_lint_pass { $( if !cx.sess().contains_name(&krate.item.attrs, $attr) { cx.lint(CRATE_NOT_OKAY, |lint| { + let span = cx.tcx.hir().span(rustc_hir::CRATE_HIR_ID); let msg = format!("crate is not marked with #![{}]", $attr); - lint.build(&msg).set_span(krate.item.span).emit() + lint.build(&msg).set_span(span).emit() }); } )* diff --git a/src/test/ui-fulldeps/auxiliary/lint-for-crate.rs b/src/test/ui-fulldeps/auxiliary/lint-for-crate.rs index bd477b793fc70..abe85ff8f0e27 100644 --- a/src/test/ui-fulldeps/auxiliary/lint-for-crate.rs +++ b/src/test/ui-fulldeps/auxiliary/lint-for-crate.rs @@ -29,8 +29,9 @@ impl<'tcx> LateLintPass<'tcx> for Pass { fn check_crate(&mut self, cx: &LateContext, krate: &rustc_hir::Crate) { if !cx.sess().contains_name(&krate.item.attrs, Symbol::intern("crate_okay")) { cx.lint(CRATE_NOT_OKAY, |lint| { + let span = cx.tcx.hir().span(rustc_hir::CRATE_HIR_ID); lint.build("crate is not marked with #![crate_okay]") - .set_span(krate.item.span) + .set_span(span) .emit() }); } diff --git a/src/tools/clippy/clippy_lints/src/blocks_in_if_conditions.rs b/src/tools/clippy/clippy_lints/src/blocks_in_if_conditions.rs index 736730d4084f4..c4195e9d32151 100644 --- a/src/tools/clippy/clippy_lints/src/blocks_in_if_conditions.rs +++ b/src/tools/clippy/clippy_lints/src/blocks_in_if_conditions.rs @@ -106,7 +106,7 @@ impl<'tcx> LateLintPass<'tcx> for BlocksInIfConditions { ); } } else { - let span = block.expr.as_ref().map_or_else(|| block.stmts[0].span, |e| e.span); + let span = block.expr.as_ref().map_or_else(|| cx.tcx.hir().span(block.stmts[0].hir_id), |e| e.span); if span.from_expansion() || differing_macro_contexts(expr.span, span) { return; } @@ -122,7 +122,7 @@ impl<'tcx> LateLintPass<'tcx> for BlocksInIfConditions { "let res = {}; if res", snippet_block_with_applicability( cx, - block.span, + cx.tcx.hir().span(block.hir_id), "..", Some(expr.span), &mut applicability diff --git a/src/tools/clippy/clippy_lints/src/booleans.rs b/src/tools/clippy/clippy_lints/src/booleans.rs index 90bb0bd555f27..1f798ec9b3c51 100644 --- a/src/tools/clippy/clippy_lints/src/booleans.rs +++ b/src/tools/clippy/clippy_lints/src/booleans.rs @@ -10,7 +10,6 @@ use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, HirId, UnOp}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::source_map::Span; use rustc_span::sym; declare_clippy_lint! { @@ -63,7 +62,6 @@ impl<'tcx> LateLintPass<'tcx> for NonminimalBool { _: FnKind<'tcx>, _: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - _: Span, _: HirId, ) { NonminimalBoolVisitor { cx }.visit_body(body) diff --git a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs index b1bc2ec29e16e..357f697356e0f 100644 --- a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs +++ b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs @@ -119,11 +119,11 @@ impl<'tcx> LateLintPass<'tcx> for CognitiveComplexity { kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - span: Span, hir_id: HirId, ) { let def_id = cx.tcx.hir().local_def_id(hir_id); if !cx.tcx.has_attr(def_id.to_def_id(), sym::test) { + let span = cx.tcx.hir().span(hir_id); self.check(cx, kind, decl, body, span); } } diff --git a/src/tools/clippy/clippy_lints/src/collapsible_match.rs b/src/tools/clippy/clippy_lints/src/collapsible_match.rs index a34ba2d00a8c7..133ba0265b017 100644 --- a/src/tools/clippy/clippy_lints/src/collapsible_match.rs +++ b/src/tools/clippy/clippy_lints/src/collapsible_match.rs @@ -6,7 +6,7 @@ use rustc_hir::{Arm, Expr, ExprKind, Guard, HirId, Pat, PatKind, QPath, StmtKind use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{DefIdTree, TyCtxt}; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::{MultiSpan, Span}; +use rustc_span::MultiSpan; declare_clippy_lint! { /// **What it does:** Finds nested `match` or `if let` expressions where the patterns may be "collapsed" together @@ -65,7 +65,7 @@ fn check_arm(arm: &Arm<'_>, wild_outer_arm: &Arm<'_>, cx: &LateContext<'_>) { let expr = strip_singleton_blocks(arm.body); if let ExprKind::Match(expr_in, arms_inner, _) = expr.kind; // the outer arm pattern and the inner match - if expr_in.span.ctxt() == arm.pat.span.ctxt(); + if expr_in.span.ctxt() == cx.tcx.hir().span(arm.pat.hir_id).ctxt(); // there must be no more than two arms in the inner match for this lint if arms_inner.len() == 2; // no if guards on the inner match @@ -95,9 +95,10 @@ fn check_arm(arm: &Arm<'_>, wild_outer_arm: &Arm<'_>, cx: &LateContext<'_>) { expr.span, "Unnecessary nested match", |diag| { - let mut help_span = MultiSpan::from_spans(vec![binding_span, non_wild_inner_arm.pat.span]); + let binding_span = cx.tcx.hir().span(binding_span); + let mut help_span = MultiSpan::from_spans(vec![binding_span, cx.tcx.hir().span(non_wild_inner_arm.pat.hir_id)]); help_span.push_span_label(binding_span, "Replace this binding".into()); - help_span.push_span_label(non_wild_inner_arm.pat.span, "with this pattern".into()); + help_span.push_span_label(cx.tcx.hir().span(non_wild_inner_arm.pat.hir_id), "with this pattern".into()); diag.span_help(help_span, "The outer pattern can be modified to include the inner pattern."); }, ); @@ -133,7 +134,7 @@ fn arm_is_wild_like(arm: &Arm<'_>, tcx: TyCtxt<'_>) -> bool { } } -fn find_pat_binding(pat: &Pat<'_>, hir_id: HirId) -> Option { +fn find_pat_binding(pat: &Pat<'_>, hir_id: HirId) -> Option { let mut span = None; pat.walk_short(|p| match &p.kind { // ignore OR patterns @@ -141,7 +142,7 @@ fn find_pat_binding(pat: &Pat<'_>, hir_id: HirId) -> Option { PatKind::Binding(_bm, _, _ident, _) => { let found = p.hir_id == hir_id; if found { - span = Some(p.span); + span = Some(p.hir_id); } !found }, diff --git a/src/tools/clippy/clippy_lints/src/copies.rs b/src/tools/clippy/clippy_lints/src/copies.rs index 46ce92ea6d782..10c72a388a734 100644 --- a/src/tools/clippy/clippy_lints/src/copies.rs +++ b/src/tools/clippy/clippy_lints/src/copies.rs @@ -134,9 +134,9 @@ fn lint_same_then_else(cx: &LateContext<'_>, blocks: &[&Block<'_>]) { span_lint_and_note( cx, IF_SAME_THEN_ELSE, - j.span, + cx.tcx.hir().span(j.hir_id), "this `if` has identical blocks", - Some(i.span), + Some(cx.tcx.hir().span(i.hir_id)), "same as this", ); } diff --git a/src/tools/clippy/clippy_lints/src/default.rs b/src/tools/clippy/clippy_lints/src/default.rs index b0d7c7b3baab1..a1fa0e11d69f2 100644 --- a/src/tools/clippy/clippy_lints/src/default.rs +++ b/src/tools/clippy/clippy_lints/src/default.rs @@ -204,12 +204,14 @@ impl LateLintPass<'_> for Default { }; // span lint once per statement that binds default + let first_assign_span = cx.tcx.hir().span(first_assign.unwrap().hir_id); + let local_span = cx.tcx.hir().span(local.hir_id); span_lint_and_note( cx, FIELD_REASSIGN_WITH_DEFAULT, - first_assign.unwrap().span, + first_assign_span, "field assignment outside of initializer for an instance created with Default::default()", - Some(local.span), + Some(local_span), &format!( "consider initializing the variable with `{}` and removing relevant reassignments", sugg diff --git a/src/tools/clippy/clippy_lints/src/derive.rs b/src/tools/clippy/clippy_lints/src/derive.rs index c75efc6e99f89..d786db464f9a9 100644 --- a/src/tools/clippy/clippy_lints/src/derive.rs +++ b/src/tools/clippy/clippy_lints/src/derive.rs @@ -382,7 +382,7 @@ struct UnsafeVisitor<'a, 'tcx> { impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> { type Map = Map<'tcx>; - fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, span: Span, id: HirId) { + fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, id: HirId) { if self.has_unsafe { return; } @@ -395,7 +395,7 @@ impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> { } } - walk_fn(self, kind, decl, body_id, span, id); + walk_fn(self, kind, decl, body_id, id); } fn visit_expr(&mut self, expr: &'tcx Expr<'_>) { diff --git a/src/tools/clippy/clippy_lints/src/enum_clike.rs b/src/tools/clippy/clippy_lints/src/enum_clike.rs index fb80f48a9ccf3..d7555267a2c9e 100644 --- a/src/tools/clippy/clippy_lints/src/enum_clike.rs +++ b/src/tools/clippy/clippy_lints/src/enum_clike.rs @@ -71,7 +71,7 @@ impl<'tcx> LateLintPass<'tcx> for UnportableVariant { span_lint( cx, ENUM_CLIKE_UNPORTABLE_VARIANT, - var.span, + cx.tcx.hir().span(var.id), "C-like enum variant discriminant is not portable to 32-bit targets", ); }; diff --git a/src/tools/clippy/clippy_lints/src/eq_op.rs b/src/tools/clippy/clippy_lints/src/eq_op.rs index 6308f6e2e7e9d..089b512d9b85e 100644 --- a/src/tools/clippy/clippy_lints/src/eq_op.rs +++ b/src/tools/clippy/clippy_lints/src/eq_op.rs @@ -69,7 +69,8 @@ impl<'tcx> LateLintPass<'tcx> for EqOp { for stmt in block.stmts { for amn in &ASSERT_MACRO_NAMES { if_chain! { - if is_expn_of(stmt.span, amn).is_some(); + let stmt_span = cx.tcx.hir().span(stmt.hir_id); + if is_expn_of(stmt_span, amn).is_some(); if let StmtKind::Semi(ref matchexpr) = stmt.kind; if let Some(macro_args) = higher::extract_assert_macro_args(matchexpr); if macro_args.len() == 2; diff --git a/src/tools/clippy/clippy_lints/src/escape.rs b/src/tools/clippy/clippy_lints/src/escape.rs index d2dcb3e5c4644..b3389be3761ac 100644 --- a/src/tools/clippy/clippy_lints/src/escape.rs +++ b/src/tools/clippy/clippy_lints/src/escape.rs @@ -4,7 +4,6 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, Ty}; use rustc_session::{declare_tool_lint, impl_lint_pass}; -use rustc_span::source_map::Span; use rustc_target::abi::LayoutOf; use rustc_target::spec::abi::Abi; use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; @@ -63,7 +62,6 @@ impl<'tcx> LateLintPass<'tcx> for BoxedLocal { fn_kind: intravisit::FnKind<'tcx>, _: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - _: Span, hir_id: HirId, ) { if let Some(header) = fn_kind.header() { diff --git a/src/tools/clippy/clippy_lints/src/functions.rs b/src/tools/clippy/clippy_lints/src/functions.rs index fd93548b55c6d..d349b4e573aba 100644 --- a/src/tools/clippy/clippy_lints/src/functions.rs +++ b/src/tools/clippy/clippy_lints/src/functions.rs @@ -247,7 +247,6 @@ impl<'tcx> LateLintPass<'tcx> for Functions { kind: intravisit::FnKind<'tcx>, decl: &'tcx hir::FnDecl<'_>, body: &'tcx hir::Body<'_>, - span: Span, hir_id: hir::HirId, ) { let unsafety = match kind { @@ -256,6 +255,8 @@ impl<'tcx> LateLintPass<'tcx> for Functions { intravisit::FnKind::Closure(_) => return, }; + let span = cx.tcx.hir().span_with_body(hir_id); + // don't warn for implementations, it's not their fault if !is_trait_impl_item(cx, hir_id) { // don't lint extern functions decls, it's not their fault either @@ -577,8 +578,9 @@ fn is_mutable_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, tys: &mut FxHashSet< if let hir::PatKind::Wild = pat.kind { return false; // ignore `_` patterns } + let pat_span = cx.tcx.hir().span(pat.hir_id); if cx.tcx.has_typeck_results(pat.hir_id.owner.to_def_id()) { - is_mutable_ty(cx, &cx.tcx.typeck(pat.hir_id.owner).pat_ty(pat), pat.span, tys) + is_mutable_ty(cx, &cx.tcx.typeck(pat.hir_id.owner).pat_ty(pat), pat_span, tys) } else { false } diff --git a/src/tools/clippy/clippy_lints/src/future_not_send.rs b/src/tools/clippy/clippy_lints/src/future_not_send.rs index f9697afe40525..907924fcc799b 100644 --- a/src/tools/clippy/clippy_lints/src/future_not_send.rs +++ b/src/tools/clippy/clippy_lints/src/future_not_send.rs @@ -6,7 +6,7 @@ use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::subst::Subst; use rustc_middle::ty::{Opaque, PredicateAtom::Trait}; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::{sym, Span}; +use rustc_span::sym; use rustc_trait_selection::traits::error_reporting::suggestions::InferCtxtExt; use rustc_trait_selection::traits::{self, FulfillmentError, TraitEngine}; @@ -55,7 +55,6 @@ impl<'tcx> LateLintPass<'tcx> for FutureNotSend { kind: FnKind<'tcx>, decl: &'tcx FnDecl<'tcx>, _: &'tcx Body<'tcx>, - _: Span, hir_id: HirId, ) { if let FnKind::Closure(_) = kind { diff --git a/src/tools/clippy/clippy_lints/src/if_let_some_result.rs b/src/tools/clippy/clippy_lints/src/if_let_some_result.rs index 1194bd7e55e25..bad295c57c428 100644 --- a/src/tools/clippy/clippy_lints/src/if_let_some_result.rs +++ b/src/tools/clippy/clippy_lints/src/if_let_some_result.rs @@ -50,7 +50,7 @@ impl<'tcx> LateLintPass<'tcx> for OkIfLet { then { let mut applicability = Applicability::MachineApplicable; - let some_expr_string = snippet_with_applicability(cx, y[0].span, "", &mut applicability); + let some_expr_string = snippet_with_applicability(cx, cx.tcx.hir().span(y[0].hir_id), "", &mut applicability); let trimmed_ok = snippet_with_applicability(cx, op.span.until(ok_span), "", &mut applicability); let sugg = format!( "if let Ok({}) = {}", diff --git a/src/tools/clippy/clippy_lints/src/implicit_return.rs b/src/tools/clippy/clippy_lints/src/implicit_return.rs index 03e95c9e27f6a..47797640ee7b8 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_return.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_return.rs @@ -123,8 +123,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitReturn { _: FnKind<'tcx>, _: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - span: Span, - _: HirId, + hir_id: HirId, ) { let def_id = cx.tcx.hir().body_owner_def_id(body.id()); @@ -134,6 +133,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitReturn { } let mir = cx.tcx.optimized_mir(def_id.to_def_id()); + let span = cx.tcx.hir().span(hir_id); // checking return type through MIR, HIR is not able to determine inferred closure return types // make sure it's not a macro diff --git a/src/tools/clippy/clippy_lints/src/large_enum_variant.rs b/src/tools/clippy/clippy_lints/src/large_enum_variant.rs index ad9b4f357a74d..34dfd48b69195 100644 --- a/src/tools/clippy/clippy_lints/src/large_enum_variant.rs +++ b/src/tools/clippy/clippy_lints/src/large_enum_variant.rs @@ -100,15 +100,15 @@ impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { span_lint_and_then( cx, LARGE_ENUM_VARIANT, - def.variants[i].span, + cx.tcx.hir().span(def.variants[i].id), "large size difference between variants", |diag| { diag.span_label( - def.variants[(largest.1).0].span, + cx.tcx.hir().span(def.variants[(largest.1).0].id), &format!("this variant is {} bytes", largest.0), ); diag.span_note( - def.variants[(second.1).0].span, + cx.tcx.hir().span(def.variants[(second.1).0].id), &format!("and the second-largest variant is {} bytes:", second.0), ); if variant.fields.len() == 1 { @@ -128,7 +128,7 @@ impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { return; } } - diag.span_help(def.variants[i].span, help_text); + diag.span_help(cx.tcx.hir().span(def.variants[i].id), help_text); }, ); } diff --git a/src/tools/clippy/clippy_lints/src/let_if_seq.rs b/src/tools/clippy/clippy_lints/src/let_if_seq.rs index 0d2d95324c4f7..7182d858dcd0d 100644 --- a/src/tools/clippy/clippy_lints/src/let_if_seq.rs +++ b/src/tools/clippy/clippy_lints/src/let_if_seq.rs @@ -70,7 +70,7 @@ impl<'tcx> LateLintPass<'tcx> for LetIfSeq { if let Some(value) = check_assign(cx, canonical_id, &*then); if !LocalUsedVisitor::new(canonical_id).check_expr(value); then { - let span = stmt.span.to(if_.span); + let span = cx.tcx.hir().span(stmt.hir_id).to(if_.span); let has_interior_mutability = !cx.typeck_results().node_type(canonical_id).is_freeze( cx.tcx.at(span), diff --git a/src/tools/clippy/clippy_lints/src/let_underscore.rs b/src/tools/clippy/clippy_lints/src/let_underscore.rs index 6a5a77f8690a9..5dd8efbd42952 100644 --- a/src/tools/clippy/clippy_lints/src/let_underscore.rs +++ b/src/tools/clippy/clippy_lints/src/let_underscore.rs @@ -109,7 +109,8 @@ const SYNC_GUARD_PATHS: [&[&str]; 3] = [ impl<'tcx> LateLintPass<'tcx> for LetUnderscore { fn check_local(&mut self, cx: &LateContext<'_>, local: &Local<'_>) { - if in_external_macro(cx.tcx.sess, local.span) { + let local_span = cx.tcx.hir().span(local.hir_id); + if in_external_macro(cx.tcx.sess, local_span) { return; } @@ -138,7 +139,7 @@ impl<'tcx> LateLintPass<'tcx> for LetUnderscore { span_lint_and_help( cx, LET_UNDERSCORE_LOCK, - local.span, + local_span, "non-binding let on a synchronization lock", None, "consider using an underscore-prefixed named \ @@ -148,7 +149,7 @@ impl<'tcx> LateLintPass<'tcx> for LetUnderscore { span_lint_and_help( cx, LET_UNDERSCORE_DROP, - local.span, + local_span, "non-binding `let` on a type that implements `Drop`", None, "consider using an underscore-prefixed named \ @@ -158,7 +159,7 @@ impl<'tcx> LateLintPass<'tcx> for LetUnderscore { span_lint_and_help( cx, LET_UNDERSCORE_MUST_USE, - local.span, + local_span, "non-binding let on an expression with `#[must_use]` type", None, "consider explicitly using expression value" @@ -167,7 +168,7 @@ impl<'tcx> LateLintPass<'tcx> for LetUnderscore { span_lint_and_help( cx, LET_UNDERSCORE_MUST_USE, - local.span, + local_span, "non-binding let on a result of a `#[must_use]` function", None, "consider explicitly using function result" diff --git a/src/tools/clippy/clippy_lints/src/lifetimes.rs b/src/tools/clippy/clippy_lints/src/lifetimes.rs index e84c8b4e5b3e0..a80bdbc9248ed 100644 --- a/src/tools/clippy/clippy_lints/src/lifetimes.rs +++ b/src/tools/clippy/clippy_lints/src/lifetimes.rs @@ -473,7 +473,7 @@ fn report_extra_lifetimes<'tcx>(cx: &LateContext<'tcx>, func: &'tcx FnDecl<'_>, .params .iter() .filter_map(|par| match par.kind { - GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)), + GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, cx.tcx.hir().span(par.hir_id))), _ => None, }) .collect(); diff --git a/src/tools/clippy/clippy_lints/src/loops.rs b/src/tools/clippy/clippy_lints/src/loops.rs index 1bd96b2b4c89b..c00653761b8cd 100644 --- a/src/tools/clippy/clippy_lints/src/loops.rs +++ b/src/tools/clippy/clippy_lints/src/loops.rs @@ -586,7 +586,7 @@ impl<'tcx> LateLintPass<'tcx> for Loops { "try", format!( "while let {} = {} {{ .. }}", - snippet_with_applicability(cx, arms[0].pat.span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(arms[0].pat.hir_id), "..", &mut applicability), snippet_with_applicability(cx, matchexpr.span, "..", &mut applicability), ), applicability, @@ -632,7 +632,7 @@ impl<'tcx> LateLintPass<'tcx> for Loops { let loop_var = if pat_args.is_empty() { "_".to_string() } else { - snippet_with_applicability(cx, pat_args[0].span, "_", &mut applicability).into_owned() + snippet_with_applicability(cx, cx.tcx.hir().span(pat_args[0].hir_id), "_", &mut applicability).into_owned() }; span_lint_and_sugg( cx, @@ -1584,7 +1584,7 @@ fn check_for_loop_range<'tcx>( diag, "consider using an iterator", vec![ - (pat.span, format!("({}, )", ident.name)), + (cx.tcx.hir().span(pat.hir_id), format!("({}, )", ident.name)), ( arg.span, format!("{}.{}().enumerate(){}{}", indexed, method, method_1, method_2), @@ -1612,7 +1612,7 @@ fn check_for_loop_range<'tcx>( multispan_sugg( diag, "consider using an iterator", - vec![(pat.span, "".to_string()), (arg.span, repl)], + vec![(cx.tcx.hir().span(pat.hir_id), "".to_string()), (arg.span, repl)], ); }, ); @@ -1748,7 +1748,7 @@ fn check_arg_type(cx: &LateContext<'_>, pat: &Pat<'_>, arg: &Expr<'_>) { None, &format!( "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`", - snippet(cx, pat.span, "_"), + snippet(cx, cx.tcx.hir().span(pat.hir_id), "_"), snippet(cx, arg.span, "_") ), ); @@ -1765,7 +1765,7 @@ fn check_arg_type(cx: &LateContext<'_>, pat: &Pat<'_>, arg: &Expr<'_>) { None, &format!( "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`", - snippet(cx, pat.span, "_"), + snippet(cx, cx.tcx.hir().span(pat.hir_id), "_"), snippet(cx, arg.span, "_") ), ); @@ -1810,7 +1810,7 @@ fn check_for_loop_explicit_counter<'tcx>( format!( "for ({}, {}) in {}.enumerate()", name, - snippet_with_applicability(cx, pat.span, "item", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(pat.hir_id), "item", &mut applicability), make_iterator_snippet(cx, arg, &mut applicability), ), applicability, @@ -1865,15 +1865,15 @@ fn check_for_loop_over_map_kv<'tcx>( body: &'tcx Expr<'_>, expr: &'tcx Expr<'_>, ) { - let pat_span = pat.span; + let pat_span = cx.tcx.hir().span(pat.hir_id); if let PatKind::Tuple(ref pat, _) = pat.kind { if pat.len() == 2 { let arg_span = arg.span; let (new_pat_span, kind, ty, mutbl) = match *cx.typeck_results().expr_ty(arg).kind() { ty::Ref(_, ty, mutbl) => match (&pat[0].kind, &pat[1].kind) { - (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", ty, mutbl), - (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", ty, Mutability::Not), + (key, _) if pat_is_wild(key, body) => (cx.tcx.hir().span(pat[1].hir_id), "value", ty, mutbl), + (_, value) if pat_is_wild(value, body) => (cx.tcx.hir().span(pat[0].hir_id), "key", ty, Mutability::Not), _ => return, }, _ => return, @@ -1928,18 +1928,19 @@ fn check_for_single_element_loop<'tcx>( then { let for_span = get_span_of_entire_for_loop(expr); - let mut block_str = snippet(cx, block.span, "..").into_owned(); + let block_span = cx.tcx.hir().span(block.hir_id); + let mut block_str = snippet(cx, block_span, "..").into_owned(); block_str.remove(0); block_str.pop(); - + let first_span = cx.tcx.hir().span(block.stmts[0].hir_id); span_lint_and_sugg( cx, SINGLE_ELEMENT_LOOP, for_span, "for loop over a single element", "try", - format!("{{\n{}let {} = &{};{}}}", " ".repeat(indent_of(cx, block.stmts[0].span).unwrap_or(0)), target.name, list_item_name, block_str), + format!("{{\n{}let {} = &{};{}}}", " ".repeat(indent_of(cx, first_span).unwrap_or(0)), target.name, list_item_name, block_str), Applicability::MachineApplicable ) } @@ -2949,17 +2950,18 @@ fn check_needless_collect_indirect_usage<'tcx>(expr: &'tcx Expr<'_>, cx: &LateCo // Suggest replacing iter_call with iter_replacement, and removing stmt let iter_call = &iter_calls[0]; + let stmt_span = cx.tcx.hir().span(stmt.hir_id); span_lint_and_then( cx, NEEDLESS_COLLECT, - stmt.span.until(iter_call.span), + stmt_span.until(iter_call.span), NEEDLESS_COLLECT_MSG, |diag| { let iter_replacement = format!("{}{}", Sugg::hir(cx, iter_source, ".."), iter_call.get_iter_method(cx)); diag.multipart_suggestion( iter_call.get_suggestion_text(), vec![ - (stmt.span, String::new()), + (stmt_span, String::new()), (iter_call.span, iter_replacement) ], Applicability::MachineApplicable,// MaybeIncorrect, diff --git a/src/tools/clippy/clippy_lints/src/macro_use.rs b/src/tools/clippy/clippy_lints/src/macro_use.rs index bb52888883af5..a9abb32774573 100644 --- a/src/tools/clippy/clippy_lints/src/macro_use.rs +++ b/src/tools/clippy/clippy_lints/src/macro_use.rs @@ -138,13 +138,15 @@ impl<'tcx> LateLintPass<'tcx> for MacroUseImports { } } fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &hir::Stmt<'_>) { - if in_macro(stmt.span) { - self.push_unique_macro(cx, stmt.span); + let stmt_span = cx.tcx.hir().span(stmt.hir_id); + if in_macro(stmt_span) { + self.push_unique_macro(cx, stmt_span); } } fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) { - if in_macro(pat.span) { - self.push_unique_macro_pat_ty(cx, pat.span); + let pat_span = cx.tcx.hir().span(pat.hir_id); + if in_macro(pat_span) { + self.push_unique_macro_pat_ty(cx, pat_span); } } fn check_ty(&mut self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) { diff --git a/src/tools/clippy/clippy_lints/src/manual_async_fn.rs b/src/tools/clippy/clippy_lints/src/manual_async_fn.rs index 29439e52c48e1..5c9052f5a07e6 100644 --- a/src/tools/clippy/clippy_lints/src/manual_async_fn.rs +++ b/src/tools/clippy/clippy_lints/src/manual_async_fn.rs @@ -9,7 +9,6 @@ use rustc_hir::{ }; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::Span; declare_clippy_lint! { /// **What it does:** It checks for manual implementations of `async` functions. @@ -43,8 +42,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualAsyncFn { kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - span: Span, - _: HirId, + hir_id: HirId, ) { if_chain! { if let Some(header) = kind.header(); @@ -59,6 +57,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualAsyncFn { if block.stmts.is_empty(); if let Some(closure_body) = desugared_async_block(cx, block); then { + let span = cx.tcx.hir().span(hir_id); let header_span = span.with_hi(ret_ty.span.hi()); span_lint_and_then( @@ -80,9 +79,10 @@ impl<'tcx> LateLintPass<'tcx> for ManualAsyncFn { Applicability::MachineApplicable ); - let body_snip = snippet_block(cx, closure_body.value.span, "..", Some(block.span)); + let block_span = cx.tcx.hir().span(block.hir_id); + let body_snip = snippet_block(cx, closure_body.value.span, "..", Some(block_span)); diag.span_suggestion( - block.span, + block_span, "move the body of the async block to the enclosing function", body_snip.to_string(), Applicability::MachineApplicable diff --git a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs index e50d11a4d7175..e021feb868df9 100644 --- a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs +++ b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs @@ -141,9 +141,9 @@ fn reduce_unit_expression<'a>(cx: &LateContext<'_>, expr: &'a hir::Expr<'_>) -> // If block only contains statements, // reduce `{ X; }` to `X` or `X;` match inner_stmt.kind { - hir::StmtKind::Local(ref local) => Some(local.span), + hir::StmtKind::Local(ref local) => Some(cx.tcx.hir().span(local.hir_id)), hir::StmtKind::Expr(ref e) => Some(e.span), - hir::StmtKind::Semi(..) => Some(inner_stmt.span), + hir::StmtKind::Semi(..) => Some(cx.tcx.hir().span(inner_stmt.hir_id)), hir::StmtKind::Item(..) => None, } }, @@ -216,6 +216,7 @@ fn lint_map_unit_fn(cx: &LateContext<'_>, stmt: &hir::Stmt<'_>, expr: &hir::Expr }; let fn_arg = &map_args[1]; + let stmt_span = cx.tcx.hir().span(stmt.hir_id); if is_unit_function(cx, fn_arg) { let msg = suggestion_msg("function", map_type); let suggestion = format!( @@ -227,7 +228,7 @@ fn lint_map_unit_fn(cx: &LateContext<'_>, stmt: &hir::Stmt<'_>, expr: &hir::Expr ); span_lint_and_then(cx, lint, expr.span, &msg, |diag| { - diag.span_suggestion(stmt.span, "try this", suggestion, Applicability::MachineApplicable); + diag.span_suggestion(stmt_span, "try this", suggestion, Applicability::MachineApplicable); }); } else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) { let msg = suggestion_msg("closure", map_type); @@ -237,12 +238,12 @@ fn lint_map_unit_fn(cx: &LateContext<'_>, stmt: &hir::Stmt<'_>, expr: &hir::Expr let suggestion = format!( "if let {0}({1}) = {2} {{ {3} }}", variant, - snippet(cx, binding.pat.span, "_"), + snippet(cx, cx.tcx.hir().span(binding.pat.hir_id), "_"), snippet(cx, var_arg.span, "_"), snippet(cx, reduced_expr_span, "_") ); diag.span_suggestion( - stmt.span, + stmt_span, "try this", suggestion, Applicability::MachineApplicable, // snippet @@ -251,10 +252,10 @@ fn lint_map_unit_fn(cx: &LateContext<'_>, stmt: &hir::Stmt<'_>, expr: &hir::Expr let suggestion = format!( "if let {0}({1}) = {2} {{ ... }}", variant, - snippet(cx, binding.pat.span, "_"), + snippet(cx, cx.tcx.hir().span(binding.pat.hir_id), "_"), snippet(cx, var_arg.span, "_"), ); - diag.span_suggestion(stmt.span, "try this", suggestion, Applicability::HasPlaceholders); + diag.span_suggestion(stmt_span, "try this", suggestion, Applicability::HasPlaceholders); } }); } @@ -262,7 +263,7 @@ fn lint_map_unit_fn(cx: &LateContext<'_>, stmt: &hir::Stmt<'_>, expr: &hir::Expr impl<'tcx> LateLintPass<'tcx> for MapUnit { fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &hir::Stmt<'_>) { - if stmt.span.from_expansion() { + if cx.tcx.hir().span(stmt.hir_id).from_expansion() { return; } diff --git a/src/tools/clippy/clippy_lints/src/matches.rs b/src/tools/clippy/clippy_lints/src/matches.rs index 04b35835c6b8e..1f458ad297bff 100644 --- a/src/tools/clippy/clippy_lints/src/matches.rs +++ b/src/tools/clippy/clippy_lints/src/matches.rs @@ -607,9 +607,10 @@ impl<'tcx> LateLintPass<'tcx> for Matches { } fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) { + let local_span = cx.tcx.hir().span(local.hir_id); if_chain! { - if !in_external_macro(cx.sess(), local.span); - if !in_macro(local.span); + if !in_external_macro(cx.sess(), local_span); + if !in_macro(local_span); if let Some(ref expr) = local.init; if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.kind; if arms.len() == 1 && arms[0].guard.is_none(); @@ -626,15 +627,15 @@ impl<'tcx> LateLintPass<'tcx> for Matches { span_lint_and_sugg( cx, INFALLIBLE_DESTRUCTURING_MATCH, - local.span, + local_span, "you seem to be trying to use `match` to destructure a single infallible pattern. \ Consider using `let`", "try this", format!( "let {}({}) = {};", snippet_with_applicability(cx, variant_name.span, "..", &mut applicability), - snippet_with_applicability(cx, local.pat.span, "..", &mut applicability), - snippet_with_applicability(cx, target.span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(local.pat.hir_id), "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(target.hir_id), "..", &mut applicability), ), applicability, ); @@ -643,9 +644,10 @@ impl<'tcx> LateLintPass<'tcx> for Matches { } fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) { + let pat_span = cx.tcx.hir().span(pat.hir_id); if_chain! { - if !in_external_macro(cx.sess(), pat.span); - if !in_macro(pat.span); + if !in_external_macro(cx.sess(), pat_span); + if !in_macro(pat_span); if let PatKind::Struct(QPath::Resolved(_, ref path), fields, true) = pat.kind; if let Some(def_id) = path.res.opt_def_id(); let ty = cx.tcx.type_of(def_id); @@ -657,7 +659,7 @@ impl<'tcx> LateLintPass<'tcx> for Matches { span_lint_and_help( cx, REST_PAT_IN_FULLY_BOUND_STRUCTS, - pat.span, + pat_span, "unnecessary use of `..` pattern in struct binding. All fields were already bound", None, "consider removing `..` from this binding", @@ -737,7 +739,7 @@ fn report_single_match_single_pattern( "try this", format!( "if let {} = {} {}{}", - snippet(cx, arms[0].pat.span, ".."), + snippet(cx, cx.tcx.hir().span(arms[0].pat.hir_id), ".."), snippet(cx, ex.span, ".."), expr_block(cx, &arms[0].body, None, "..", Some(expr.span)), els_str, @@ -893,12 +895,12 @@ fn check_wild_err_arm(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) { if_chain! { if matching_wild; if let ExprKind::Block(ref block, _) = arm.body.kind; - if is_panic_block(block); + if is_panic_block(cx, block); then { // `Err(_)` or `Err(_e)` arm with `panic!` found span_lint_and_note(cx, MATCH_WILD_ERR_ARM, - arm.pat.span, + cx.tcx.hir().span(arm.pat.hir_id), &format!("`Err({})` matches all errors", &ident_bind_name), None, "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable", @@ -925,9 +927,9 @@ fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) let mut wildcard_ident = None; for arm in arms { if let PatKind::Wild = arm.pat.kind { - wildcard_span = Some(arm.pat.span); + wildcard_span = Some(cx.tcx.hir().span(arm.pat.hir_id)); } else if let PatKind::Binding(_, _, ident, None) = arm.pat.kind { - wildcard_span = Some(arm.pat.span); + wildcard_span = Some(cx.tcx.hir().span(arm.pat.hir_id)); wildcard_ident = Some(ident); } } @@ -1022,13 +1024,14 @@ fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) } // If the block contains only a `panic!` macro (as expression or statement) -fn is_panic_block(block: &Block<'_>) -> bool { +fn is_panic_block(cx: &LateContext<'_>, block: &Block<'_>) -> bool { match (&block.expr, block.stmts.len(), block.stmts.first()) { (&Some(ref exp), 0, _) => { is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none() }, (&None, 1, Some(stmt)) => { - is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none() + let stmt_span = cx.tcx.hir().span(stmt.hir_id); + is_expn_of(stmt_span, "panic").is_some() && is_expn_of(stmt_span, "unreachable").is_none() }, _ => false, } @@ -1055,7 +1058,10 @@ fn check_match_ref_pats(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], e suggs.extend(arms.iter().filter_map(|a| { if let PatKind::Ref(ref refp, _) = a.pat.kind { - Some((a.pat.span, snippet(cx, refp.span, "..").to_string())) + Some(( + cx.tcx.hir().span(a.pat.hir_id), + snippet(cx, cx.tcx.hir().span(refp.hir_id), "..").to_string(), + )) } else { None } @@ -1129,7 +1135,7 @@ fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) { span_lint_and_help( cx, WILDCARD_IN_OR_PATTERNS, - arm.pat.span, + cx.tcx.hir().span(arm.pat.hir_id), "wildcard pattern covers any other pattern as it will match anyway.", None, "Consider handling `_` separately.", @@ -1177,7 +1183,7 @@ fn find_matches_sugg(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr let pat = { use itertools::Itertools as _; b0_arms.iter() - .map(|arm| snippet_with_applicability(cx, arm.pat.span, "..", &mut applicability)) + .map(|arm| snippet_with_applicability(cx, cx.tcx.hir().span(arm.pat.hir_id), "..", &mut applicability)) .join(" | ") }; let pat_and_guard = if let Some(Guard::If(g)) = if_guard { @@ -1244,7 +1250,7 @@ fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[A // a macro. See PR #6435 if_chain! { if let Some(match_snippet) = snippet_opt(cx, expr.span); - if let Some(arm_snippet) = snippet_opt(cx, arms[0].span); + if let Some(arm_snippet) = snippet_opt(cx, cx.tcx.hir().span(arms[0].hir_id)); if let Some(ex_snippet) = snippet_opt(cx, ex.span); let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, ""); if rest_snippet.contains("=>"); @@ -1256,7 +1262,7 @@ fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[A } let matched_vars = ex.span; - let bind_names = arms[0].pat.span; + let bind_names = cx.tcx.hir().span(arms[0].pat.hir_id); let match_body = remove_blocks(&arms[0].body); let mut snippet_body = if match_body.span.from_expansion() { Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string() @@ -1268,7 +1274,8 @@ fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[A match match_body.kind { ExprKind::Block(block, _) => { // macro + expr_ty(body) == () - if block.span.from_expansion() && cx.typeck_results().expr_ty(&match_body).is_unit() { + let block_span = cx.tcx.hir().span(block.hir_id); + if block_span.from_expansion() && cx.typeck_results().expr_ty(&match_body).is_unit() { snippet_body.push(';'); } }, @@ -1286,13 +1293,18 @@ fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[A // If this match is in a local (`let`) stmt let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) { ( - parent_let_node.span, + cx.tcx.hir().span(parent_let_node.hir_id), format!( "let {} = {};\n{}let {} = {};", snippet_with_applicability(cx, bind_names, "..", &mut applicability), snippet_with_applicability(cx, matched_vars, "..", &mut applicability), " ".repeat(indent_of(cx, expr.span).unwrap_or(0)), - snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability), + snippet_with_applicability( + cx, + cx.tcx.hir().span(parent_let_node.pat.hir_id), + "..", + &mut applicability + ), snippet_body ), ) @@ -1381,7 +1393,7 @@ fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) RangeEnd::Excluded => Bound::Excluded(rhs), }; return Some(SpannedRange { - span: pat.span, + span: cx.tcx.hir().span(pat.hir_id), node: (lhs, rhs), }); } @@ -1389,7 +1401,7 @@ fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) if let PatKind::Lit(ref value) = pat.kind { let value = constant(cx, cx.typeck_results(), value)?.0; return Some(SpannedRange { - span: pat.span, + span: cx.tcx.hir().span(pat.hir_id), node: (value.clone(), Bound::Included(value)), }); } @@ -1631,7 +1643,7 @@ mod redundant_pattern_match { span_lint_and_then( cx, REDUNDANT_PATTERN_MATCHING, - arms[0].pat.span, + cx.tcx.hir().span(arms[0].pat.hir_id), &format!("redundant pattern matching, consider using `{}`", good_method), |diag| { // while let ... = ... { ... } @@ -1855,8 +1867,8 @@ fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) { // span for the whole pattern, the suggestion is only shown when there is only // one pattern. The user should know about `|` if they are already using it… - let lhs = snippet(cx, i.pat.span, ""); - let rhs = snippet(cx, j.pat.span, ""); + let lhs = snippet(cx, cx.tcx.hir().span(i.pat.hir_id), ""); + let rhs = snippet(cx, cx.tcx.hir().span(j.pat.hir_id), ""); if let PatKind::Wild = j.pat.kind { // if the last arm is _, then i could be integrated into _ @@ -1870,7 +1882,10 @@ fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) { ), ); } else { - diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs)); + diag.span_help( + cx.tcx.hir().span(i.pat.hir_id), + &format!("consider refactoring into `{} | {}`", lhs, rhs), + ); } }, ); diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index e99fe1b97ff64..7332784eb213c 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -1680,7 +1680,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { item.vis.node.is_pub(), self_ty, first_arg_ty, - first_arg.pat.span + cx.tcx.hir().span(first_arg.pat.hir_id) ); } } diff --git a/src/tools/clippy/clippy_lints/src/misc.rs b/src/tools/clippy/clippy_lints/src/misc.rs index 0512d74c7b1c8..13a682aea7dc2 100644 --- a/src/tools/clippy/clippy_lints/src/misc.rs +++ b/src/tools/clippy/clippy_lints/src/misc.rs @@ -275,13 +275,13 @@ impl<'tcx> LateLintPass<'tcx> for MiscLints { k: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - span: Span, - _: HirId, + hir_id: HirId, ) { if let FnKind::Closure(_) = k { // Does not apply to closures return; } + let span = cx.tcx.hir().span(hir_id); if in_external_macro(cx.tcx.sess, span) { return; } @@ -290,7 +290,7 @@ impl<'tcx> LateLintPass<'tcx> for MiscLints { span_lint( cx, TOPLEVEL_REF_ARG, - arg.pat.span, + cx.tcx.hir().span(arg.pat.hir_id), "`ref` directly on a function argument is ignored. \ Consider using a reference type instead.", ); @@ -300,7 +300,8 @@ impl<'tcx> LateLintPass<'tcx> for MiscLints { fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) { if_chain! { - if !in_external_macro(cx.tcx.sess, stmt.span); + let stmt_span = cx.tcx.hir().span(stmt.hir_id); + if !in_external_macro(cx.tcx.sess, stmt_span); if let StmtKind::Local(ref local) = stmt.kind; if let PatKind::Binding(an, .., name, None) = local.pat.kind; if let Some(ref init) = local.init; @@ -309,7 +310,8 @@ impl<'tcx> LateLintPass<'tcx> for MiscLints { if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut { // use the macro callsite when the init span (but not the whole local span) // comes from an expansion like `vec![1, 2, 3]` in `let ref _ = vec![1, 2, 3];` - let sugg_init = if init.span.from_expansion() && !local.span.from_expansion() { + let local_span = cx.tcx.hir().span(local.hir_id); + let sugg_init = if init.span.from_expansion() && !local_span.from_expansion() { Sugg::hir_with_macro_callsite(cx, init, "..") } else { Sugg::hir(cx, init, "..") @@ -328,11 +330,11 @@ impl<'tcx> LateLintPass<'tcx> for MiscLints { cx, TOPLEVEL_REF_ARG, init.hir_id, - local.pat.span, + cx.tcx.hir().span(local.pat.hir_id), "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead", |diag| { diag.span_suggestion( - stmt.span, + cx.tcx.hir().span(stmt.hir_id), "try", format!( "let {name}{tyopt} = {initref};", @@ -353,14 +355,15 @@ impl<'tcx> LateLintPass<'tcx> for MiscLints { if binop.node == BinOpKind::And || binop.node == BinOpKind::Or; if let Some(sugg) = Sugg::hir_opt(cx, a); then { + let stmt_span = cx.tcx.hir().span(stmt.hir_id); span_lint_and_then(cx, SHORT_CIRCUIT_STATEMENT, - stmt.span, + stmt_span, "boolean short circuit operator in statement may be clearer using an explicit test", |diag| { let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg }; diag.span_suggestion( - stmt.span, + stmt_span, "replace it with", format!( "if {} {{ {}; }}", diff --git a/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs b/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs index 6ebeaced62a33..d1102542dd1d9 100644 --- a/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs +++ b/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs @@ -9,7 +9,6 @@ use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::lint::in_external_macro; use rustc_semver::RustcVersion; use rustc_session::{declare_tool_lint, impl_lint_pass}; -use rustc_span::Span; use rustc_typeck::hir_ty_to_ty; const MISSING_CONST_FOR_FN_MSRV: RustcVersion = RustcVersion::new(1, 37, 0); @@ -94,7 +93,6 @@ impl<'tcx> LateLintPass<'tcx> for MissingConstForFn { kind: FnKind<'_>, _: &FnDecl<'_>, _: &Body<'_>, - span: Span, hir_id: HirId, ) { if !meets_msrv(self.msrv.as_ref(), &MISSING_CONST_FOR_FN_MSRV) { @@ -102,6 +100,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingConstForFn { } let def_id = cx.tcx.hir().local_def_id(hir_id); + let span = cx.tcx.hir().span_with_body(hir_id); if in_external_macro(cx.tcx.sess, span) || is_entrypoint_fn(cx, def_id.to_def_id()) { return; diff --git a/src/tools/clippy/clippy_lints/src/missing_doc.rs b/src/tools/clippy/clippy_lints/src/missing_doc.rs index 27f1074a0dd8a..018735726523c 100644 --- a/src/tools/clippy/clippy_lints/src/missing_doc.rs +++ b/src/tools/clippy/clippy_lints/src/missing_doc.rs @@ -127,7 +127,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { } fn check_crate(&mut self, cx: &LateContext<'tcx>, krate: &'tcx hir::Crate<'_>) { - self.check_missing_docs_attrs(cx, &krate.item.attrs, krate.item.span, "the", "crate"); + self.check_missing_docs_attrs(cx, &krate.item.attrs, cx.tcx.hir().span(hir::CRATE_HIR_ID), "the", "crate"); } fn check_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx hir::Item<'_>) { @@ -190,11 +190,11 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { fn check_struct_field(&mut self, cx: &LateContext<'tcx>, sf: &'tcx hir::StructField<'_>) { if !sf.is_positional() { - self.check_missing_docs_attrs(cx, &sf.attrs, sf.span, "a", "struct field"); + self.check_missing_docs_attrs(cx, &sf.attrs, cx.tcx.hir().span(sf.hir_id), "a", "struct field"); } } fn check_variant(&mut self, cx: &LateContext<'tcx>, v: &'tcx hir::Variant<'_>) { - self.check_missing_docs_attrs(cx, &v.attrs, v.span, "a", "variant"); + self.check_missing_docs_attrs(cx, &v.attrs, cx.tcx.hir().span(v.id), "a", "variant"); } } diff --git a/src/tools/clippy/clippy_lints/src/mut_key.rs b/src/tools/clippy/clippy_lints/src/mut_key.rs index 11044e0c2fb48..2e9a3aca6db0e 100644 --- a/src/tools/clippy/clippy_lints/src/mut_key.rs +++ b/src/tools/clippy/clippy_lints/src/mut_key.rs @@ -79,7 +79,8 @@ impl<'tcx> LateLintPass<'tcx> for MutableKeyType { if let hir::PatKind::Wild = local.pat.kind { return; } - check_ty(cx, local.span, cx.typeck_results().pat_ty(&*local.pat)); + let local_span = cx.tcx.hir().span(local.hir_id); + check_ty(cx, local_span, cx.typeck_results().pat_ty(&*local.pat)); } } diff --git a/src/tools/clippy/clippy_lints/src/needless_borrow.rs b/src/tools/clippy/clippy_lints/src/needless_borrow.rs index bff53eb8ccada..d3237f183a02b 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrow.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrow.rs @@ -84,7 +84,8 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessBorrow { } } fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) { - if pat.span.from_expansion() || self.derived_item.is_some() { + let pat_span = cx.tcx.hir().span(pat.hir_id); + if pat_span.from_expansion() || self.derived_item.is_some() { return; } if_chain! { @@ -98,12 +99,12 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessBorrow { span_lint_and_then( cx, NEEDLESS_BORROW, - pat.span, + pat_span, "this pattern creates a reference to a reference", |diag| { if let Some(snippet) = snippet_opt(cx, name.span) { diag.span_suggestion( - pat.span, + pat_span, "change this to", snippet, Applicability::MachineApplicable, diff --git a/src/tools/clippy/clippy_lints/src/needless_borrowed_ref.rs b/src/tools/clippy/clippy_lints/src/needless_borrowed_ref.rs index 85184fdea4779..c0e00783e72a4 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrowed_ref.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrowed_ref.rs @@ -54,7 +54,8 @@ declare_lint_pass!(NeedlessBorrowedRef => [NEEDLESS_BORROWED_REFERENCE]); impl<'tcx> LateLintPass<'tcx> for NeedlessBorrowedRef { fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) { - if pat.span.from_expansion() { + let pat_span = cx.tcx.hir().span(pat.hir_id); + if pat_span.from_expansion() { // OK, simple enough, lints doesn't check in macro. return; } @@ -75,12 +76,12 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessBorrowedRef { return; } let mut applicability = Applicability::MachineApplicable; - span_lint_and_then(cx, NEEDLESS_BORROWED_REFERENCE, pat.span, + span_lint_and_then(cx, NEEDLESS_BORROWED_REFERENCE, pat_span, "this pattern takes a reference on something that is being de-referenced", |diag| { let hint = snippet_with_applicability(cx, spanned_name.span, "..", &mut applicability).into_owned(); diag.span_suggestion( - pat.span, + pat_span, "try removing the `&ref` part and just keep", hint, applicability, diff --git a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs index 5043b7b1fc3c1..97e430cff5a76 100644 --- a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs +++ b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs @@ -71,9 +71,9 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - span: Span, hir_id: HirId, ) { + let span = cx.tcx.hir().span(hir_id); if span.from_expansion() { return; } diff --git a/src/tools/clippy/clippy_lints/src/no_effect.rs b/src/tools/clippy/clippy_lints/src/no_effect.rs index b1b5b3439a0e3..3ec18e8f21f79 100644 --- a/src/tools/clippy/clippy_lints/src/no_effect.rs +++ b/src/tools/clippy/clippy_lints/src/no_effect.rs @@ -92,7 +92,7 @@ impl<'tcx> LateLintPass<'tcx> for NoEffect { fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) { if let StmtKind::Semi(ref expr) = stmt.kind { if has_no_effect(cx, expr) { - span_lint(cx, NO_EFFECT, stmt.span, "statement with no effect"); + span_lint(cx, NO_EFFECT, cx.tcx.hir().span(stmt.hir_id), "statement with no effect"); } else if let Some(reduced) = reduce_expression(cx, expr) { let mut snippet = String::new(); for e in reduced { @@ -109,7 +109,7 @@ impl<'tcx> LateLintPass<'tcx> for NoEffect { span_lint_and_sugg( cx, UNNECESSARY_OPERATION, - stmt.span, + cx.tcx.hir().span(stmt.hir_id), "statement can be reduced", "replace it with", snippet, diff --git a/src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs b/src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs index 37e2b50def17a..0e04845c5b580 100644 --- a/src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs +++ b/src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs @@ -40,12 +40,12 @@ impl<'tcx> LateLintPass<'tcx> for PanicInResultFn { fn_kind: FnKind<'tcx>, _: &'tcx hir::FnDecl<'tcx>, body: &'tcx hir::Body<'tcx>, - span: Span, hir_id: hir::HirId, ) { if !matches!(fn_kind, FnKind::Closure(_)) && is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) { + let span = cx.tcx.hir().span_with_body(hir_id); lint_impl_body(cx, span, body); } } 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 ceecc8dbc06fc..043d40a0f0aae 100644 --- a/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs +++ b/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs @@ -45,7 +45,7 @@ impl<'tcx> LateLintPass<'tcx> for PartialEqNeImpl { cx, PARTIALEQ_NE_IMPL, impl_item.id.hir_id, - impl_item.span, + cx.tcx.hir().span_with_body(impl_item.id.hir_id), "re-implementing `PartialEq::ne` is unnecessary", ); } diff --git a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs index 6a17d654ac943..737ee91b299c4 100644 --- a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs +++ b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs @@ -216,9 +216,9 @@ impl<'tcx> LateLintPass<'tcx> for PassByRefOrValue { kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, _body: &'tcx Body<'_>, - span: Span, hir_id: HirId, ) { + let span = cx.tcx.hir().span(hir_id); if span.from_expansion() { return; } diff --git a/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs b/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs index 5539331d0460b..a24a30cf23568 100644 --- a/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs +++ b/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs @@ -89,7 +89,8 @@ impl<'tcx> LateLintPass<'tcx> for PatternTypeMismatch { if let Some(init) = &local.init { if let Some(init_ty) = cx.typeck_results().node_type_opt(init.hir_id) { let pat = &local.pat; - if in_external_macro(cx.sess(), pat.span) { + let pat_span = cx.tcx.hir().span(pat.hir_id); + if in_external_macro(cx.sess(), pat_span) { return; } let deref_possible = match local.source { @@ -109,7 +110,8 @@ impl<'tcx> LateLintPass<'tcx> for PatternTypeMismatch { if let Some(expr_ty) = cx.typeck_results().node_type_opt(expr.hir_id) { 'pattern_checks: for arm in arms { let pat = &arm.pat; - if in_external_macro(cx.sess(), pat.span) { + let pat_span = cx.tcx.hir().span(pat.hir_id); + if in_external_macro(cx.sess(), pat_span) { continue 'pattern_checks; } if apply_lint(cx, pat, expr_ty, DerefPossible::Possible) { @@ -129,7 +131,6 @@ impl<'tcx> LateLintPass<'tcx> for PatternTypeMismatch { _: intravisit::FnKind<'tcx>, _: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - _: Span, hir_id: HirId, ) { if let Some(fn_sig) = cx.typeck_results().liberated_fn_sigs().get(hir_id) { @@ -194,7 +195,8 @@ fn find_first_mismatch<'tcx>( if let TyKind::Ref(_, _, mutability) = *ty.kind() { if is_non_ref_pattern(&pat.kind) { - return Some((pat.span, mutability, level)); + let pat_span = cx.tcx.hir().span(pat.hir_id); + return Some((pat_span, mutability, level)); } } diff --git a/src/tools/clippy/clippy_lints/src/redundant_clone.rs b/src/tools/clippy/clippy_lints/src/redundant_clone.rs index 06adbb523d706..bcfb249d07d0d 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_clone.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_clone.rs @@ -16,7 +16,7 @@ use rustc_middle::mir::{ use rustc_middle::ty::{self, fold::TypeVisitor, Ty}; use rustc_mir::dataflow::{Analysis, AnalysisDomain, GenKill, GenKillAnalysis, ResultsCursor}; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::source_map::{BytePos, Span}; +use rustc_span::source_map::BytePos; use rustc_span::sym; use std::convert::TryFrom; use std::ops::ControlFlow; @@ -75,7 +75,6 @@ impl<'tcx> LateLintPass<'tcx> for RedundantClone { _: FnKind<'tcx>, _: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - _: Span, _: HirId, ) { let def_id = cx.tcx.hir().body_owner_def_id(body.id()); diff --git a/src/tools/clippy/clippy_lints/src/returns.rs b/src/tools/clippy/clippy_lints/src/returns.rs index 7f4913a02cbd3..627d1f5e75af2 100644 --- a/src/tools/clippy/clippy_lints/src/returns.rs +++ b/src/tools/clippy/clippy_lints/src/returns.rs @@ -89,8 +89,9 @@ impl<'tcx> LateLintPass<'tcx> for Return { if !last_statement_borrows(cx, initexpr); if !in_external_macro(cx.sess(), initexpr.span); if !in_external_macro(cx.sess(), retexpr.span); - if !in_external_macro(cx.sess(), local.span); - if !in_macro(local.span); + let local_span = cx.tcx.hir().span(local.hir_id); + if !in_external_macro(cx.sess(), local_span); + if !in_macro(local_span); then { span_lint_and_then( cx, @@ -98,7 +99,7 @@ impl<'tcx> LateLintPass<'tcx> for Return { retexpr.span, "returning the result of a `let` binding from a block", |err| { - err.span_label(local.span, "unnecessary `let` binding"); + err.span_label(local_span, "unnecessary `let` binding"); if let Some(mut snippet) = snippet_opt(cx, initexpr.span) { if !cx.typeck_results().expr_adjustments(&retexpr).is_empty() { @@ -107,7 +108,7 @@ impl<'tcx> LateLintPass<'tcx> for Return { err.multipart_suggestion( "return the expression directly", vec![ - (local.span, String::new()), + (local_span, String::new()), (retexpr.span, snippet), ], Applicability::MachineApplicable, @@ -127,7 +128,6 @@ impl<'tcx> LateLintPass<'tcx> for Return { kind: FnKind<'tcx>, _: &'tcx FnDecl<'tcx>, body: &'tcx Body<'tcx>, - _: Span, _: HirId, ) { match kind { @@ -151,7 +151,8 @@ fn check_block_return<'tcx>(cx: &LateContext<'tcx>, block: &Block<'tcx>) { } else if let Some(stmt) = block.stmts.iter().last() { match stmt.kind { StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => { - check_final_expr(cx, expr, Some(stmt.span), RetReplacement::Empty); + let stmt_span = cx.tcx.hir().span(stmt.hir_id); + check_final_expr(cx, expr, Some(stmt_span), RetReplacement::Empty); }, _ => (), } diff --git a/src/tools/clippy/clippy_lints/src/serde_api.rs b/src/tools/clippy/clippy_lints/src/serde_api.rs index 339a7cf3bf5d2..f44c4c2c314cd 100644 --- a/src/tools/clippy/clippy_lints/src/serde_api.rs +++ b/src/tools/clippy/clippy_lints/src/serde_api.rs @@ -35,8 +35,8 @@ impl<'tcx> LateLintPass<'tcx> for SerdeAPI { let mut seen_string = None; for item in items { match &*item.ident.as_str() { - "visit_str" => seen_str = Some(item.span), - "visit_string" => seen_string = Some(item.span), + "visit_str" => seen_str = Some(cx.tcx.hir().span_with_body(item.id.hir_id)), + "visit_string" => seen_string = Some(cx.tcx.hir().span_with_body(item.id.hir_id)), _ => {}, } } diff --git a/src/tools/clippy/clippy_lints/src/shadow.rs b/src/tools/clippy/clippy_lints/src/shadow.rs index f839659267825..a96857e967be1 100644 --- a/src/tools/clippy/clippy_lints/src/shadow.rs +++ b/src/tools/clippy/clippy_lints/src/shadow.rs @@ -104,7 +104,6 @@ impl<'tcx> LateLintPass<'tcx> for Shadow { _: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - _: Span, _: HirId, ) { if in_external_macro(cx.sess(), body.value.span) { @@ -140,7 +139,8 @@ fn check_block<'tcx>(cx: &LateContext<'tcx>, block: &'tcx Block<'_>, bindings: & } fn check_local<'tcx>(cx: &LateContext<'tcx>, local: &'tcx Local<'_>, bindings: &mut Vec<(Symbol, Span)>) { - if in_external_macro(cx.sess(), local.span) { + let span = cx.tcx.hir().span(local.hir_id); + if in_external_macro(cx.sess(), span) { return; } if higher::is_from_for_desugar(local) { @@ -150,7 +150,6 @@ fn check_local<'tcx>(cx: &LateContext<'tcx>, local: &'tcx Local<'_>, bindings: & ref pat, ref ty, ref init, - span, .. } = *local; if let Some(ref t) = *ty { @@ -184,7 +183,7 @@ fn check_pat<'tcx>( let mut new_binding = true; for tup in bindings.iter_mut() { if tup.0 == name { - lint_shadow(cx, name, span, pat.span, init, tup.1); + lint_shadow(cx, name, span, cx.tcx.hir().span(pat.hir_id), init, tup.1); tup.1 = ident.span; new_binding = false; break; @@ -223,7 +222,7 @@ fn check_pat<'tcx>( if let Some(init_tup) = init { if let ExprKind::Tup(ref tup) = init_tup.kind { for (i, p) in inner.iter().enumerate() { - check_pat(cx, p, Some(&tup[i]), p.span, bindings); + check_pat(cx, p, Some(&tup[i]), cx.tcx.hir().span(p.hir_id), bindings); } } else { for p in inner { @@ -337,13 +336,13 @@ fn check_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, bindings: &mut check_expr(cx, init, bindings); let len = bindings.len(); for arm in arms { - check_pat(cx, &arm.pat, Some(&**init), arm.pat.span, bindings); + check_pat(cx, &arm.pat, Some(&**init), cx.tcx.hir().span(arm.pat.hir_id), bindings); // This is ugly, but needed to get the right type if let Some(ref guard) = arm.guard { match guard { Guard::If(if_expr) => check_expr(cx, if_expr, bindings), Guard::IfLet(guard_pat, guard_expr) => { - check_pat(cx, guard_pat, Some(*guard_expr), guard_pat.span, bindings); + check_pat(cx, guard_pat, Some(*guard_expr), cx.tcx.hir().span(guard_pat.hir_id), bindings); check_expr(cx, guard_expr, bindings); }, } diff --git a/src/tools/clippy/clippy_lints/src/swap.rs b/src/tools/clippy/clippy_lints/src/swap.rs index 386987eb181ea..5b611a100e710 100644 --- a/src/tools/clippy/clippy_lints/src/swap.rs +++ b/src/tools/clippy/clippy_lints/src/swap.rs @@ -133,7 +133,7 @@ fn check_manual_swap(cx: &LateContext<'_>, block: &Block<'_>) { (true, String::new(), String::new()) }; - let span = w[0].span.to(second.span); + let span = cx.tcx.hir().span(w[0].hir_id).to(second.span); span_lint_and_then( cx, diff --git a/src/tools/clippy/clippy_lints/src/types.rs b/src/tools/clippy/clippy_lints/src/types.rs index fd74783335d57..dabaca4fa07b9 100644 --- a/src/tools/clippy/clippy_lints/src/types.rs +++ b/src/tools/clippy/clippy_lints/src/types.rs @@ -255,7 +255,7 @@ pub struct Types { impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION, RC_BUFFER]); impl<'tcx> LateLintPass<'tcx> for Types { - fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, _: Span, id: HirId) { + fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, id: HirId) { // Skip trait implementations; see issue #605. if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) { if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind { @@ -774,7 +774,8 @@ impl<'tcx> LateLintPass<'tcx> for LetUnitValue { fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) { if let StmtKind::Local(ref local) = stmt.kind { if is_unit(cx.typeck_results().pat_ty(&local.pat)) { - if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() { + let stmt_span = cx.tcx.hir().span(stmt.hir_id); + if in_external_macro(cx.sess(), stmt_span) || cx.tcx.hir().span(local.pat.hir_id).from_expansion() { return; } if higher::is_from_for_desugar(local) { @@ -783,13 +784,13 @@ impl<'tcx> LateLintPass<'tcx> for LetUnitValue { span_lint_and_then( cx, LET_UNIT_VALUE, - stmt.span, + stmt_span, "this let-binding has unit value", |diag| { if let Some(expr) = &local.init { let snip = snippet_with_macro_callsite(cx, expr.span, "()"); diag.span_suggestion( - stmt.span, + stmt_span, "omit the `let` binding", format!("{};", snip), Applicability::MachineApplicable, // snippet @@ -1032,7 +1033,7 @@ fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Exp if let Some(snip) = snippet_opt(cx, last_expr.span); then { Some(( - last_stmt.span, + cx.tcx.hir().span(last_stmt.hir_id), snip, )) } @@ -1902,7 +1903,6 @@ impl<'tcx> LateLintPass<'tcx> for TypeComplexity { _: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, _: &'tcx Body<'_>, - _: Span, _: HirId, ) { self.check_fndecl(cx, decl); @@ -2613,7 +2613,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitHasher { continue; } let generics_suggestion_span = generics.span.substitute_dummy({ - let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span)) + let pos = snippet_opt(cx, item.span.until(cx.tcx.hir().span(body.params[0].pat.hir_id))) .and_then(|snip| { let i = snip.find("fn")?; Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32)) diff --git a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs index 2501635e7ef66..940dc701623bf 100644 --- a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs +++ b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs @@ -122,7 +122,7 @@ fn check_arg<'tcx>(cx: &LateContext<'tcx>, arg: &'tcx Expr<'tcx>) -> Option<(Spa if let Some(stmt) = block.stmts.last(); if let StmtKind::Semi(_) = stmt.kind; then { - let data = stmt.span.data(); + let data = cx.tcx.hir().span(stmt.hir_id).data(); // Make a span out of the semicolon for the help message Some((span, Some(Span::new(data.hi-BytePos(1), data.hi, data.ctxt)))) } else { diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs index 5b9a80f92db69..c5461832766ed 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs @@ -10,7 +10,6 @@ use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::subst::GenericArgKind; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::sym; -use rustc_span::Span; declare_clippy_lint! { /// **What it does:** Checks for private functions that only return `Ok` or `Some`. @@ -61,7 +60,6 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryWraps { fn_kind: FnKind<'tcx>, fn_decl: &FnDecl<'tcx>, body: &Body<'tcx>, - span: Span, hir_id: HirId, ) { match fn_kind { @@ -113,7 +111,7 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryWraps { span_lint_and_then( cx, UNNECESSARY_WRAPS, - span, + cx.tcx.hir().span_with_body(hir_id), format!( "this function's return value is unnecessarily wrapped by `{}`", return_type diff --git a/src/tools/clippy/clippy_lints/src/unused_self.rs b/src/tools/clippy/clippy_lints/src/unused_self.rs index da7517125c13b..b002698d027e0 100644 --- a/src/tools/clippy/clippy_lints/src/unused_self.rs +++ b/src/tools/clippy/clippy_lints/src/unused_self.rs @@ -67,7 +67,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedSelf { span_lint_and_help( cx, UNUSED_SELF, - self_param.span, + cx.tcx.hir().span(self_param.hir_id), "unused `self` argument", None, "consider refactoring to a associated function", diff --git a/src/tools/clippy/clippy_lints/src/unwrap.rs b/src/tools/clippy/clippy_lints/src/unwrap.rs index f4a77e54dd149..3d6780ee6a9f2 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap.rs @@ -10,7 +10,6 @@ use rustc_middle::hir::map::Map; use rustc_middle::lint::in_external_macro; use rustc_middle::ty::Ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::source_map::Span; use rustc_span::sym; declare_clippy_lint! { @@ -217,9 +216,9 @@ impl<'tcx> LateLintPass<'tcx> for Unwrap { kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - span: Span, fn_id: HirId, ) { + let span = cx.tcx.hir().span(fn_id); if span.from_expansion() { return; } @@ -229,6 +228,6 @@ impl<'tcx> LateLintPass<'tcx> for Unwrap { unwrappables: Vec::new(), }; - walk_fn(&mut v, kind, decl, body.id(), span, fn_id); + walk_fn(&mut v, kind, decl, body.id(), fn_id); } } diff --git a/src/tools/clippy/clippy_lints/src/utils/mod.rs b/src/tools/clippy/clippy_lints/src/utils/mod.rs index 1c68e837c4ab9..8589246bb2857 100644 --- a/src/tools/clippy/clippy_lints/src/utils/mod.rs +++ b/src/tools/clippy/clippy_lints/src/utils/mod.rs @@ -556,7 +556,7 @@ struct ContainsName { impl<'tcx> Visitor<'tcx> for ContainsName { type Map = Map<'tcx>; - fn visit_name(&mut self, _: Span, name: Symbol) { + fn visit_name(&mut self, name: Symbol) { if self.name == name { self.result = true; }