From 596450ee18797ab26a5b64e30889e0b7a76cca9f Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Fri, 1 May 2020 22:40:01 +0200 Subject: [PATCH 01/41] Collect spans during lowering. Collect spans directly into an IndexVec. --- compiler/rustc_ast_lowering/src/expr.rs | 44 +++--- compiler/rustc_ast_lowering/src/item.rs | 49 +++--- compiler/rustc_ast_lowering/src/lib.rs | 144 +++++++++++------- compiler/rustc_ast_lowering/src/pat.rs | 6 +- compiler/rustc_ast_lowering/src/path.rs | 10 +- compiler/rustc_hir/src/hir.rs | 4 + .../rustc_middle/src/hir/map/collector.rs | 1 + 7 files changed, 151 insertions(+), 107 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 43b93d03ff6fb..91feff6a29bdf 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -256,6 +256,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. if !e.attrs.is_empty() { @@ -281,7 +282,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span), }; - let hir_id = self.lower_node_id(e.id); + let hir_id = self.lower_node_id(e.id, e.span); self.lower_attrs(hir_id, &e.attrs); hir::Expr { hir_id, kind, span: e.span } }) @@ -624,7 +625,7 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::Guard::If(self.lower_expr(cond)) } }); - let hir_id = self.next_id(); + let hir_id = self.next_id(arm.span); self.lower_attrs(hir_id, &arm.attrs); hir::Arm { hir_id, pat, guard, body: self.lower_expr(&arm.body), span: arm.span } } @@ -654,7 +655,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 { @@ -670,7 +671,7 @@ impl<'hir> LoweringContext<'_, 'hir> { Ident::with_dummy_span(sym::_task_context), hir::BindingAnnotation::Mutable, ); - let param = hir::Param { hir_id: self.next_id(), pat, ty_span: span, span }; + let param = hir::Param { hir_id: self.next_id(span), pat, ty_span: span, span }; let params = arena_vec![self; param]; let body_id = self.lower_body(move |this| { @@ -691,8 +692,11 @@ impl<'hir> LoweringContext<'_, 'hir> { span, Some(hir::Movability::Static), ); - let generator = - hir::Expr { hir_id: self.lower_node_id(closure_node_id), kind: generator_kind, span }; + let generator = hir::Expr { + hir_id: self.lower_node_id(closure_node_id, span), + kind: generator_kind, + span, + }; // `future::from_generator`: let unstable_span = @@ -785,7 +789,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); @@ -1114,7 +1118,7 @@ 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, @@ -1255,7 +1259,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) } @@ -1264,7 +1268,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 } @@ -1660,7 +1664,7 @@ 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, @@ -1725,6 +1729,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); @@ -1815,8 +1820,11 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::LoopSource::ForLoop, e.span.with_hi(orig_head_span.hi()), ); - let loop_expr = - self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: e.span }); + let loop_expr = self.arena.alloc(hir::Expr { + hir_id: self.lower_node_id(e.id, e.span), + kind, + span: e.span, + }); // `mut iter => { ... }` let iter_arm = self.arm(iter_pat, loop_expr); @@ -1939,7 +1947,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( @@ -2112,8 +2120,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( @@ -2151,16 +2159,16 @@ impl<'hir> LoweringContext<'_, 'hir> { kind: hir::ExprKind<'hir>, attrs: AttrVec, ) -> hir::Expr<'hir> { - let hir_id = self.next_id(); + let hir_id = self.next_id(span); self.lower_attrs(hir_id, &attrs); hir::Expr { hir_id, kind, span } } 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, span, 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(), pat, guard: None, span: expr.span, body: expr } + hir::Arm { hir_id: self.next_id(expr.span), pat, guard: None, span: expr.span, body: expr } } } diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index f656325f68181..ec31d346a6a7a 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -13,12 +13,11 @@ 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}; -use tracing::debug; - use std::mem; +use tracing::debug; pub(super) struct ItemLowerer<'a, 'lowering, 'hir> { pub(super) lctx: &'a mut LoweringContext<'lowering, 'hir>, @@ -50,7 +49,7 @@ impl<'a> Visitor<'a> for ItemLowerer<'a, '_, '_> { let this = &mut ItemLowerer { lctx: this }; match item.kind { ItemKind::Mod(..) => { - let def_id = this.lctx.lower_node_id(item.id).expect_owner(); + let def_id = this.lctx.lower_node_id(item.id, item.span).expect_owner(); let old_current_module = mem::replace(&mut this.lctx.current_module, def_id); visit::walk_item(this, item); @@ -220,7 +219,7 @@ 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); self.lower_attrs(hir_id, &i.attrs); let body = P(self.lower_mac_args(body)); self.exported_macros.push(hir::MacroDef { @@ -239,7 +238,7 @@ impl<'hir> LoweringContext<'_, 'hir> { return None; } - let hir_id = self.lower_node_id(i.id); + let hir_id = self.lower_node_id(i.id, i.span); let attrs = self.lower_attrs(hir_id, &i.attrs); let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, &mut vis, &i.kind); Some(hir::Item { def_id: hir_id.expect_owner(), ident, kind, vis, span: i.span }) @@ -398,7 +397,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_def_id = self.lower_node_id(id).expect_owner(); + let lowered_trait_def_id = self.lower_node_id(id, DUMMY_SP).expect_owner(); let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs( ast_generics, lowered_trait_def_id, @@ -546,7 +545,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); @@ -605,7 +604,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(); @@ -676,7 +675,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, @@ -692,7 +691,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), } } }; @@ -700,7 +699,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem<'hir> { - let hir_id = self.lower_node_id(i.id); + let hir_id = self.lower_node_id(i.id, i.span); let def_id = hir_id.expect_owner(); self.lower_attrs(hir_id, &i.attrs); hir::ForeignItem { @@ -738,7 +737,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef<'hir> { hir::ForeignItemRef { - id: hir::ForeignItemId { def_id: self.lower_node_id(i.id).expect_owner() }, + id: hir::ForeignItemId { def_id: self.lower_node_id(i.id, i.span).expect_owner() }, ident: i.ident, span: i.span, vis: self.lower_visibility(&i.vis, Some(i.id)), @@ -750,7 +749,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> { - let id = self.lower_node_id(v.id); + let id = self.lower_node_id(v.id, v.span); self.lower_attrs(id, &v.attrs); hir::Variant { id, @@ -773,7 +772,7 @@ impl<'hir> LoweringContext<'_, 'hir> { recovered, ), VariantData::Tuple(ref fields, id) => { - let ctor_id = self.lower_node_id(id); + let ctor_id = self.lower_node_id(id, self.spans[parent_id]); self.alias_attrs(ctor_id, parent_id); hir::VariantData::Tuple( self.arena.alloc_from_iter( @@ -783,7 +782,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ) } VariantData::Unit(id) => { - let ctor_id = self.lower_node_id(id); + let ctor_id = self.lower_node_id(id, self.spans[parent_id]); self.alias_attrs(ctor_id, parent_id); hir::VariantData::Unit(ctor_id) } @@ -803,7 +802,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } else { self.lower_ty(&f.ty, ImplTraitContext::disallowed()) }; - let hir_id = self.lower_node_id(f.id); + let hir_id = self.lower_node_id(f.id, f.span); self.lower_attrs(hir_id, &f.attrs); hir::StructField { span: f.span, @@ -819,7 +818,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } fn lower_trait_item(&mut self, i: &AssocItem) -> hir::TraitItem<'hir> { - let hir_id = self.lower_node_id(i.id); + let hir_id = self.lower_node_id(i.id, i.span); let trait_item_def_id = hir_id.expect_owner(); let (generics, kind) = match i.kind { @@ -868,7 +867,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } AssocItemKind::MacCall(..) => unimplemented!(), }; - let id = hir::TraitItemId { def_id: self.lower_node_id(i.id).expect_owner() }; + let id = hir::TraitItemId { def_id: self.lower_node_id(i.id, i.span).expect_owner() }; let defaultness = hir::Defaultness::Default { has_value: has_default }; hir::TraitItemRef { id, ident: i.ident, span: i.span, defaultness, kind } } @@ -932,7 +931,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // Since `default impl` is not yet implemented, this is always true in impls. let has_value = true; let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value); - let hir_id = self.lower_node_id(i.id); + let hir_id = self.lower_node_id(i.id, i.span); self.lower_attrs(hir_id, &i.attrs); hir::ImplItem { def_id: hir_id.expect_owner(), @@ -950,7 +949,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let has_value = true; let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value); hir::ImplItemRef { - id: hir::ImplItemId { def_id: self.lower_node_id(i.id).expect_owner() }, + id: hir::ImplItemId { def_id: self.lower_node_id(i.id, i.span).expect_owner() }, ident: i.ident, span: i.span, vis: self.lower_visibility(&i.vis, Some(i.id)), @@ -982,9 +981,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); @@ -1037,7 +1036,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> { - let hir_id = self.lower_node_id(param.id); + let hir_id = self.lower_node_id(param.id, param.span); self.lower_attrs(hir_id, ¶m.attrs); hir::Param { hir_id, @@ -1492,7 +1491,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 3a97321ceb691..9ddc7915d7ce4 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_ID}; 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, MISSING_ABI}; use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer}; @@ -60,7 +60,7 @@ use rustc_session::Session; use rustc_span::hygiene::ExpnId; use rustc_span::source_map::{respan, DesugaringKind}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::Span; +use rustc_span::{Span, DUMMY_SP}; use rustc_target::spec::abi::Abi; use smallvec::{smallvec, SmallVec}; @@ -112,6 +112,9 @@ struct LoweringContext<'a, 'hir: 'a> { modules: BTreeMap, + /// Collected spans from the AST. + spans: HirIdVec, + generator_kind: Option, attrs: BTreeMap, @@ -312,6 +315,7 @@ pub fn lower_crate<'a, 'hir>( trait_impls: BTreeMap::new(), modules: BTreeMap::new(), attrs: BTreeMap::default(), + spans: Default::default(), exported_macros: Vec::new(), non_exported_macro_attrs: Vec::new(), catch_scopes: Vec::new(), @@ -561,7 +565,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); @@ -603,6 +607,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } } + //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, span: c.span }, exported_macros: self.arena.alloc_from_iter(self.exported_macros), @@ -618,6 +626,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { proc_macros, trait_map, attrs: self.attrs, + spans: self.spans, } } @@ -632,7 +641,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 } @@ -640,6 +649,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); @@ -650,15 +660,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 { @@ -685,8 +707,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; @@ -695,8 +717,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) @@ -718,14 +745,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); }) }) @@ -844,7 +871,7 @@ 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, bounds: &[], span, @@ -1232,7 +1259,7 @@ 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, gen_args, kind, @@ -1283,9 +1310,9 @@ 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 }); } @@ -1312,7 +1339,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 { @@ -1322,7 +1349,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> { @@ -1466,7 +1493,7 @@ 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, bounds: hir_bounds, @@ -1520,7 +1547,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( @@ -1574,7 +1601,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }; trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id); - lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span); + lctx.generate_opaque_type(opaque_ty_node_id, opaque_ty_item, span, opaque_ty_span); // `impl Trait` now just becomes `Foo<'a, 'b, ..>`. hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes) @@ -1585,12 +1612,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { /// returns the lowered node-ID for the opaque type. fn generate_opaque_type( &mut self, - opaque_ty_id: LocalDefId, + opaque_ty_node_id: NodeId, opaque_ty_item: hir::OpaqueTy<'hir>, span: Span, opaque_ty_span: Span, ) { let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item); + let opaque_ty_id = self.lower_node_id(opaque_ty_node_id, opaque_ty_span).expect_owner(); // Generate an `type Foo = impl Trait;` declaration. trace!("registering opaque type with id {:#?}", opaque_ty_id); let opaque_ty_item = hir::Item { @@ -1724,14 +1752,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, @@ -1812,7 +1843,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ) }); let init = l.init.as_ref().map(|e| self.lower_expr(e)); - let hir_id = self.lower_node_id(l.id); + let hir_id = self.lower_node_id(l.id, l.span); self.lower_attrs(hir_id, &l.attrs); ( hir::Local { @@ -2084,7 +2115,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }; trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id); - this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span); + this.generate_opaque_type(opaque_ty_node_id, opaque_ty_item, span, opaque_ty_span); lifetime_params }); @@ -2110,7 +2141,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), }) @@ -2119,7 +2150,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, }))); @@ -2168,7 +2199,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // ::std::future::Future hir::LangItem::Future, span, - self.next_id(), + self.next_id(span), future_args, ) } @@ -2221,7 +2252,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>( @@ -2323,7 +2354,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } }; - let hir_id = self.lower_node_id(param.id); + let hir_id = self.lower_node_id(param.id, param.ident.span); self.lower_attrs(hir_id, ¶m.attrs); hir::GenericParam { hir_id, @@ -2344,7 +2375,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( @@ -2416,7 +2447,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let stmts = self.arena.alloc_from_iter(stmts.iter().flat_map(|stmt| self.lower_stmt(stmt))); let expr = expr.map(|e| self.lower_expr(e)); 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 } } @@ -2429,9 +2460,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 } }) } @@ -2444,12 +2476,12 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { .map(|item_id| { let item_id = hir::ItemId { // All the items that `lower_local` finds are `impl Trait` types. - def_id: self.lower_node_id(item_id).expect_owner(), + def_id: self.lower_node_id(item_id, DUMMY_SP).expect_owner(), }; self.stmt(s.span, hir::StmtKind::Item(item_id)) }) .collect(); - let hir_id = self.lower_node_id(s.id); + let hir_id = self.lower_node_id(s.id, s.span); self.alias_attrs(hir_id, l.hir_id); ids.push({ hir::Stmt { @@ -2469,8 +2501,8 @@ 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 } }) @@ -2478,13 +2510,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } StmtKind::Expr(ref e) => { let e = self.lower_expr(e); - let hir_id = self.lower_node_id(s.id); + let hir_id = self.lower_node_id(s.id, s.span); self.alias_attrs(hir_id, e.hir_id); (hir_id, hir::StmtKind::Expr(e)) } StmtKind::Semi(ref e) => { let e = self.lower_expr(e); - let hir_id = self.lower_node_id(s.id); + let hir_id = self.lower_node_id(s.id, s.span); self.alias_attrs(hir_id, e.hir_id); (hir_id, hir::StmtKind::Semi(e)) } @@ -2526,7 +2558,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 { span, kind, hir_id: self.next_id(span) } } fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> { @@ -2541,7 +2573,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { pat: &'hir hir::Pat<'hir>, source: hir::LocalSource, ) -> hir::Stmt<'hir> { - let hir_id = self.next_id(); + let hir_id = self.next_id(span); if let Some(a) = attrs { debug_assert!(!a.is_empty()); self.attrs.insert(hir_id, a); @@ -2563,7 +2595,7 @@ 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, @@ -2602,7 +2634,7 @@ 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, @@ -2631,7 +2663,7 @@ 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 { @@ -2650,7 +2682,7 @@ 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(), + hir_id: self.next_id(span), kind, span, default_binding_modes: true, @@ -2659,7 +2691,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { 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, @@ -2685,7 +2717,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), @@ -2711,7 +2743,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), } @@ -2806,7 +2838,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, }; @@ -2815,7 +2847,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..d0f04f4f28228 100644 --- a/compiler/rustc_ast_lowering/src/pat.rs +++ b/compiler/rustc_ast_lowering/src/pat.rs @@ -57,7 +57,7 @@ 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, @@ -242,7 +242,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,7 +274,7 @@ 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 cb4d5ea6ee650..4cec8cf2676ed 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)); } @@ -340,9 +340,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={:?}", @@ -429,6 +429,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let args = arena_vec![self;]; let bindings = arena_vec![self;]; let gen_args = self.arena.alloc(hir::GenericArgs { args, bindings, parenthesized: false }); - hir::TypeBinding { hir_id: self.next_id(), gen_args, span, ident, kind } + hir::TypeBinding { hir_id: self.next_id(span), gen_args, span, ident, kind } } } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 8f61adcd8e288..d0a9f3b4ca59a 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2,6 +2,7 @@ use crate::def::{CtorKind, 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; @@ -676,6 +677,9 @@ pub struct Crate<'hir> { /// Collected attributes from HIR nodes. pub attrs: BTreeMap, + + /// Collected spans from the AST. + pub spans: HirIdVec, } impl Crate<'hir> { diff --git a/compiler/rustc_middle/src/hir/map/collector.rs b/compiler/rustc_middle/src/hir/map/collector.rs index b1dd405a6be68..2238754d3f5e4 100644 --- a/compiler/rustc_middle/src/hir/map/collector.rs +++ b/compiler/rustc_middle/src/hir/map/collector.rs @@ -117,6 +117,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { proc_macros: _, trait_map: _, attrs: _, + spans: _, } = *krate; hash_body(&mut hcx, root_mod_def_path_hash, item, &mut hir_body_nodes) From 1b6618d1a8bd983a83e705357d6eeb17110cc134 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Fri, 1 May 2020 22:27:37 +0200 Subject: [PATCH 02/41] Introduce a query for HIR spans. --- compiler/rustc_middle/src/hir/map/mod.rs | 70 +++++++----------------- compiler/rustc_middle/src/hir/mod.rs | 1 + compiler/rustc_middle/src/query/mod.rs | 9 +++ 3 files changed, 29 insertions(+), 51 deletions(-) diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 41ecffb9c5604..0549c4342f535 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -13,7 +13,6 @@ use rustc_hir::itemlikevisit::ItemLikeVisitor; use rustc_hir::*; use rustc_index::vec::IndexVec; use rustc_span::hygiene::MacroKind; -use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, Ident, Symbol}; use rustc_span::Span; use rustc_target::spec::abi::Abi; @@ -861,62 +860,31 @@ impl<'hir> Map<'hir> { } pub fn opt_span(&self, hir_id: HirId) -> Option { - let span = match self.find_entry(hir_id)?.node { - Node::Param(param) => param.span, - Node::Item(item) => match &item.kind { - ItemKind::Fn(sig, _, _) => sig.span, - _ => item.span, - }, - Node::ForeignItem(foreign_item) => foreign_item.span, - Node::TraitItem(trait_item) => match &trait_item.kind { - TraitItemKind::Fn(sig, _) => sig.span, - _ => trait_item.span, - }, - Node::ImplItem(impl_item) => match &impl_item.kind { - ImplItemKind::Fn(sig, _) => sig.span, - _ => impl_item.span, - }, - Node::Variant(variant) => variant.span, - Node::Field(field) => field.span, - Node::AnonConst(constant) => self.body(constant.body).value.span, - Node::Expr(expr) => expr.span, - Node::Stmt(stmt) => stmt.span, - Node::PathSegment(seg) => seg.ident.span, - Node::Ty(ty) => ty.span, - Node::TraitRef(tr) => tr.path.span, - Node::Binding(pat) => pat.span, - Node::Pat(pat) => pat.span, - Node::Arm(arm) => arm.span, - Node::Block(block) => block.span, - Node::Ctor(..) => match self.find(self.get_parent_node(hir_id))? { - Node::Item(item) => item.span, - Node::Variant(variant) => variant.span, - _ => unreachable!(), - }, - Node::Lifetime(lifetime) => lifetime.span, - Node::GenericParam(param) => param.span, - Node::Visibility(&Spanned { - node: VisibilityKind::Restricted { ref path, .. }, - .. - }) => path.span, - Node::Visibility(v) => bug!("unexpected Visibility {:?}", v), - Node::Local(local) => local.span, - Node::MacroDef(macro_def) => macro_def.span, - Node::Crate(item) => item.span, + match self.find_entry(hir_id).map(|entry| entry.node) { + Some(Node::Item(item)) => { + if let ItemKind::Fn(sig, _, _) = &item.kind { + return Some(sig.span); + } + } + Some(Node::TraitItem(item)) => { + if let TraitItemKind::Fn(sig, _) = &item.kind { + return Some(sig.span); + } + } + Some(Node::ImplItem(item)) => { + if let ImplItemKind::Fn(sig, _) = &item.kind { + return Some(sig.span); + } + } + _ => {} }; - Some(span) + self.tcx.hir_spans(hir_id.owner).get(hir_id.local_id).copied() } /// 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_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 cf4e473d8aca1..09d238c55dc70 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -121,6 +121,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_attrs = |tcx, id| AttributeMap { map: &tcx.untracked_crate.attrs, prefix: id }; + providers.hir_spans = |tcx, id| tcx.hir_crate(LOCAL_CRATE).spans.get_owner(id); providers.def_span = |tcx, def_id| tcx.hir().span_if_local(def_id).unwrap_or(DUMMY_SP); providers.fn_arg_names = |tcx, id| { let hir = tcx.hir(); diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index b03b26d64606c..7f857ad1f4072 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -70,6 +70,15 @@ rustc_queries! { desc { |tcx| "HIR owner attributes 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_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. /// From 166bb39f8cddc4c03d5768934938a4fb766a1e6c Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 May 2020 15:02:33 +0200 Subject: [PATCH 03/41] Don't pass spans in hir::map::blocks. --- compiler/rustc_middle/src/hir/map/blocks.rs | 31 ++++++--------------- 1 file changed, 9 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_middle/src/hir/map/blocks.rs b/compiler/rustc_middle/src/hir/map/blocks.rs index 706c79009496b..2e471e105505d 100644 --- a/compiler/rustc_middle/src/hir/map/blocks.rs +++ b/compiler/rustc_middle/src/hir/map/blocks.rs @@ -16,7 +16,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). @@ -103,7 +102,6 @@ struct ItemFnParts<'a> { generics: &'a hir::Generics<'a>, body: hir::BodyId, id: hir::HirId, - span: Span, } /// These are all the components one can extract from a closure expr @@ -112,12 +110,11 @@ struct ClosureParts<'a> { decl: &'a FnDecl<'a>, body: hir::BodyId, id: hir::HirId, - span: Span, } impl<'a> ClosureParts<'a> { - fn new(d: &'a FnDecl<'a>, b: hir::BodyId, id: hir::HirId, s: Span) -> Self { - ClosureParts { decl: d, body: b, id, span: s } + fn new(d: &'a FnDecl<'a>, b: hir::BodyId, id: hir::HirId) -> Self { + ClosureParts { decl: d, body: b, id } } } @@ -137,7 +134,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, ) } @@ -145,23 +142,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, ) } @@ -184,7 +173,7 @@ impl<'a> FnLikeNode<'a> { }; let closure = |_: ClosureParts<'a>| FnKind::Closure; let method = - |_, ident: Ident, sig: &'a hir::FnSig<'a>, vis, _, _| FnKind::Method(ident, sig, vis); + |_, ident: Ident, sig: &'a hir::FnSig<'a>, vis, _| FnKind::Method(ident, sig, vis); self.handle(item, method, closure) } @@ -197,7 +186,6 @@ impl<'a> FnLikeNode<'a> { &'a hir::FnSig<'a>, Option<&'a hir::Visibility<'a>>, hir::BodyId, - Span, ) -> A, C: FnOnce(ClosureParts<'a>) -> A, { @@ -209,7 +197,6 @@ impl<'a> FnLikeNode<'a> { decl: &sig.decl, body: block, vis: &i.vis, - span: i.span, header: sig.header, generics, }), @@ -217,19 +204,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) + method(ti.hir_id(), ti.ident, sig, None, body) } _ => 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) + method(ii.hir_id(), ii.ident, sig, Some(&ii.vis), body) } _ => 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)) + closure(ClosureParts::new(&decl, block, e.hir_id)) } _ => bug!("expr FnLikeNode that is not fn-like"), }, From 46b2dc2a7d1f6b1b99a8ab9688f22dbda6dd2cc8 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 May 2020 12:35:02 +0200 Subject: [PATCH 04/41] Stop passing the Span in HIR visiting. --- compiler/rustc_ast_lowering/src/lib.rs | 6 +- compiler/rustc_hir/src/intravisit.rs | 109 ++++++------------ compiler/rustc_lint/src/builtin.rs | 22 ++-- compiler/rustc_lint/src/late.rs | 27 ++--- compiler/rustc_lint/src/lib.rs | 2 +- compiler/rustc_lint/src/nonstandard_style.rs | 11 +- compiler/rustc_lint/src/passes.rs | 9 +- compiler/rustc_lint/src/types.rs | 1 - .../rustc_middle/src/hir/map/collector.rs | 9 +- compiler/rustc_middle/src/hir/map/mod.rs | 6 +- compiler/rustc_mir/src/transform/mod.rs | 3 +- compiler/rustc_passes/src/dead.rs | 1 - compiler/rustc_passes/src/hir_stats.rs | 11 +- compiler/rustc_passes/src/naked_functions.rs | 6 +- compiler/rustc_privacy/src/lib.rs | 14 ++- compiler/rustc_resolve/src/late/lifetimes.rs | 2 +- .../rustc_save_analysis/src/dump_visitor.rs | 4 +- .../rustc_typeck/src/check/gather_locals.rs | 1 - .../rustc_typeck/src/check/method/suggest.rs | 2 +- compiler/rustc_typeck/src/check/regionck.rs | 2 +- src/tools/clippy/clippy_lints/src/booleans.rs | 2 - .../clippy_lints/src/cognitive_complexity.rs | 2 +- src/tools/clippy/clippy_lints/src/derive.rs | 4 +- src/tools/clippy/clippy_lints/src/escape.rs | 2 - .../clippy/clippy_lints/src/functions.rs | 3 +- .../clippy_lints/src/future_not_send.rs | 3 +- .../clippy_lints/src/implicit_return.rs | 5 +- .../clippy_lints/src/manual_async_fn.rs | 6 +- src/tools/clippy/clippy_lints/src/misc.rs | 4 +- .../clippy_lints/src/missing_const_for_fn.rs | 3 +- .../src/needless_pass_by_value.rs | 2 +- .../clippy_lints/src/panic_in_result_fn.rs | 2 +- .../clippy_lints/src/pass_by_ref_or_value.rs | 2 +- .../clippy_lints/src/pattern_type_mismatch.rs | 1 - .../clippy_lints/src/redundant_clone.rs | 3 +- src/tools/clippy/clippy_lints/src/returns.rs | 1 - src/tools/clippy/clippy_lints/src/shadow.rs | 1 - .../clippy/clippy_lints/src/types/mod.rs | 3 +- .../clippy_lints/src/unnecessary_wraps.rs | 3 +- src/tools/clippy/clippy_lints/src/unwrap.rs | 5 +- src/tools/clippy/clippy_utils/src/lib.rs | 2 +- 41 files changed, 121 insertions(+), 186 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 9ddc7915d7ce4..d81a76c399fa4 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1671,15 +1671,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); } } diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index df63f0d48c3dd..85bd96730cb9b 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, @@ -327,13 +326,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>) { @@ -375,8 +374,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) @@ -411,7 +410,6 @@ pub trait Visitor<'v>: Sized { _: Symbol, _: &'v Generics<'v>, _parent_id: HirId, - _: Span, ) { walk_struct_def(self, s) } @@ -423,7 +421,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) } @@ -443,17 +440,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) @@ -475,7 +472,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_macro_def, krate.exported_macros); for (&id, attrs) in krate.attrs.iter() { for a in *attrs { @@ -511,7 +508,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) { @@ -560,7 +557,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, _) => { @@ -575,12 +572,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), &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()); @@ -602,7 +598,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(Impl { unsafety: _, @@ -625,13 +621,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()); @@ -670,13 +660,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); } @@ -699,7 +683,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); @@ -720,12 +704,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); @@ -733,7 +712,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(..) => {} } @@ -741,27 +720,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); } @@ -772,7 +743,7 @@ pub fn walk_assoc_type_binding<'v, V: Visitor<'v>>( ) { visitor.visit_id(type_binding.hir_id); visitor.visit_ident(type_binding.ident); - visitor.visit_generic_args(type_binding.span, type_binding.gen_args); + visitor.visit_generic_args(type_binding.gen_args); match type_binding.kind { TypeBindingKind::Equality { ref ty } => { visitor.visit_ty(ty); @@ -787,14 +758,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); @@ -849,9 +820,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), } @@ -937,7 +908,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); @@ -967,7 +937,6 @@ pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v Trai FnKind::Method(trait_item.ident, sig, None), &sig.decl, body_id, - trait_item.span, trait_item.hir_id(), ); } @@ -1008,7 +977,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)), &sig.decl, body_id, - impl_item.span, impl_item.hir_id(), ); } @@ -1090,7 +1058,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); @@ -1106,7 +1074,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) => { @@ -1136,14 +1104,9 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>) visitor.visit_expr(subexpression); walk_list!(visitor, visit_arm, arms); } - ExprKind::Closure(_, ref function_declaration, body, _fn_decl_span, _gen) => visitor - .visit_fn( - FnKind::Closure, - function_declaration, - body, - expression.span, - expression.hir_id, - ), + ExprKind::Closure(_, ref function_declaration, body, _fn_decl_span, _gen) => { + visitor.visit_fn(FnKind::Closure, function_declaration, body, expression.hir_id) + } ExprKind::Block(ref block, ref opt_label) => { walk_list!(visitor, visit_label, opt_label); visitor.visit_block(block); @@ -1165,7 +1128,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_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index dca5e470e7fb9..a6c31c53051d8 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -1398,36 +1398,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); } } @@ -1463,7 +1469,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(); @@ -1488,7 +1494,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(); diff --git a/compiler/rustc_lint/src/late.rs b/compiler/rustc_lint/src/late.rs index 9a64737f3a25d..300b9cc82496e 100644 --- a/compiler/rustc_lint/src/late.rs +++ b/compiler/rustc_lint/src/late.rs @@ -25,7 +25,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]) { @@ -191,7 +190,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, @@ -199,9 +197,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); } @@ -212,7 +210,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); @@ -244,13 +241,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); } } @@ -391,8 +384,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 9e61c83fda3a5..93b650409c695 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -72,7 +72,7 @@ use rustc_middle::ty::TyCtxt; use rustc_session::lint::builtin::{ BARE_TRAIT_OBJECTS, ELIDED_LIFETIMES_IN_PATHS, EXPLICIT_OUTLIVES_REQUIREMENTS, }; -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 be9c6eafb6fdb..5685efbc86213 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)] @@ -323,13 +323,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; } @@ -387,7 +381,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 ffbed3a0aff2d..7d9d55dbc1d6c 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 2d311cc32f8b7..5fcc087701523 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1305,7 +1305,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; diff --git a/compiler/rustc_middle/src/hir/map/collector.rs b/compiler/rustc_middle/src/hir/map/collector.rs index 2238754d3f5e4..00b29d6efd31d 100644 --- a/compiler/rustc_middle/src/hir/map/collector.rs +++ b/compiler/rustc_middle/src/hir/map/collector.rs @@ -449,11 +449,11 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { }); } - 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(DUMMY_SP, 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>) { @@ -477,11 +477,10 @@ 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>) { diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 0549c4342f535..9f90a2e2ef2fb 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -459,11 +459,11 @@ impl<'hir> Map<'hir> { self.attrs(CRATE_HIR_ID) } - 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), } } diff --git a/compiler/rustc_mir/src/transform/mod.rs b/compiler/rustc_mir/src/transform/mod.rs index 13546442f6652..0646f880e77ed 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; @@ -122,7 +122,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_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index ca25445486d40..acce8e785a332 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -255,7 +255,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; diff --git a/compiler/rustc_passes/src/hir_stats.rs b/compiler/rustc_passes/src/hir_stats.rs index ccbfc6b166160..0111bf0bee92a 100644 --- a/compiler/rustc_passes/src/hir_stats.rs +++ b/compiler/rustc_passes/src/hir_stats.rs @@ -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/naked_functions.rs b/compiler/rustc_passes/src/naked_functions.rs index 89bc2e1a9870f..5e38ffbb41eeb 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; @@ -69,7 +68,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); } } } @@ -147,12 +146,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; diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 72be266b338ba..9c47e8e64ccde 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -857,7 +857,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() { @@ -1043,7 +1043,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` } @@ -1172,7 +1172,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` } @@ -1275,7 +1275,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)), @@ -1308,6 +1308,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(); @@ -1315,7 +1316,7 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { } } - intravisit::walk_qpath(self, qpath, id, span); + intravisit::walk_qpath(self, qpath, id); } // Check types of patterns. @@ -2077,7 +2078,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/lifetimes.rs b/compiler/rustc_resolve/src/late/lifetimes.rs index 4f92532e3a698..afaa2a535689d 100644 --- a/compiler/rustc_resolve/src/late/lifetimes.rs +++ b/compiler/rustc_resolve/src/late/lifetimes.rs @@ -2897,7 +2897,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 f943753183a54..a09b7e118568d 100644 --- a/compiler/rustc_save_analysis/src/dump_visitor.rs +++ b/compiler/rustc_save_analysis/src/dump_visitor.rs @@ -1338,7 +1338,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); @@ -1430,7 +1430,7 @@ 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); } diff --git a/compiler/rustc_typeck/src/check/gather_locals.rs b/compiler/rustc_typeck/src/check/gather_locals.rs index 825ebc19fa6da..fc420dc2c6495 100644 --- a/compiler/rustc_typeck/src/check/gather_locals.rs +++ b/compiler/rustc_typeck/src/check/gather_locals.rs @@ -133,7 +133,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/method/suggest.rs b/compiler/rustc_typeck/src/check/method/suggest.rs index 13757ac41325b..a7cbf67673186 100644 --- a/compiler/rustc_typeck/src/check/method/suggest.rs +++ b/compiler/rustc_typeck/src/check/method/suggest.rs @@ -1438,7 +1438,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/regionck.rs b/compiler/rustc_typeck/src/check/regionck.rs index 55c6420ae5e2e..e28d8f3916844 100644 --- a/compiler/rustc_typeck/src/check/regionck.rs +++ b/compiler/rustc_typeck/src/check/regionck.rs @@ -350,7 +350,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 +364,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. diff --git a/src/tools/clippy/clippy_lints/src/booleans.rs b/src/tools/clippy/clippy_lints/src/booleans.rs index 0713303ec4b67..c26e0fb2a9bb6 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 658d445dfec54..9462998e5f1a9 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/derive.rs b/src/tools/clippy/clippy_lints/src/derive.rs index 6d3094ed6bfad..ead1453e9d003 100644 --- a/src/tools/clippy/clippy_lints/src/derive.rs +++ b/src/tools/clippy/clippy_lints/src/derive.rs @@ -388,7 +388,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; } @@ -401,7 +401,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/escape.rs b/src/tools/clippy/clippy_lints/src/escape.rs index f8ef2a464d5c3..48c25175002d5 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, TraitRef, Ty}; use rustc_session::{declare_tool_lint, impl_lint_pass}; -use rustc_span::source_map::Span; use rustc_span::symbol::kw; use rustc_target::abi::LayoutOf; use rustc_target::spec::abi::Abi; @@ -65,7 +64,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 c474db06fe3fd..48e7a5f64d9cb 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(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 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 9e1a8864a3ebe..afd5177a0ea2e 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, PredicateKind::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/implicit_return.rs b/src/tools/clippy/clippy_lints/src/implicit_return.rs index b4f814e1dcccf..32b4fec462a5d 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_return.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_return.rs @@ -130,10 +130,9 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitReturn { _: FnKind<'tcx>, _: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - span: Span, - _: HirId, + hir_id: HirId, ) { - if span.from_expansion() { + if cx.tcx.hir().span(hir_id).from_expansion() { return; } let body = cx.tcx.hir().body(body.id()); 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 2e2e693592c88..b2f03c47f8918 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,7 @@ use rustc_hir::{ }; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::{sym, Span}; +use rustc_span::sym; declare_clippy_lint! { /// **What it does:** It checks for manual implementations of `async` functions. @@ -43,8 +43,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 +58,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( diff --git a/src/tools/clippy/clippy_lints/src/misc.rs b/src/tools/clippy/clippy_lints/src/misc.rs index acdc245456b5a..2310facef33c4 100644 --- a/src/tools/clippy/clippy_lints/src/misc.rs +++ b/src/tools/clippy/clippy_lints/src/misc.rs @@ -276,13 +276,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; } 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 b0998a80128ce..d01555941c682 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(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/needless_pass_by_value.rs b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs index cac4b2075114a..621e1224b028a 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 @@ -72,9 +72,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/panic_in_result_fn.rs b/src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs index 207423a186149..bab0eee52833b 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,10 +40,10 @@ 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(hir_id); lint_impl_body(cx, span, body); } } 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 ff700aa514607..b407f5bbed5f3 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..97e2e47c21124 100644 --- a/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs +++ b/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs @@ -129,7 +129,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) { diff --git a/src/tools/clippy/clippy_lints/src/redundant_clone.rs b/src/tools/clippy/clippy_lints/src/redundant_clone.rs index f90d48205633e..48eb9d9bd44ef 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 40c0f1f45895b..e1ae4aec8b915 100644 --- a/src/tools/clippy/clippy_lints/src/returns.rs +++ b/src/tools/clippy/clippy_lints/src/returns.rs @@ -127,7 +127,6 @@ impl<'tcx> LateLintPass<'tcx> for Return { kind: FnKind<'tcx>, _: &'tcx FnDecl<'tcx>, body: &'tcx Body<'tcx>, - _: Span, _: HirId, ) { match kind { diff --git a/src/tools/clippy/clippy_lints/src/shadow.rs b/src/tools/clippy/clippy_lints/src/shadow.rs index 32f6bc74642ca..3f49d6ddcd8e7 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) { diff --git a/src/tools/clippy/clippy_lints/src/types/mod.rs b/src/tools/clippy/clippy_lints/src/types/mod.rs index 13da768b0ca3e..5dc1f1c245d19 100644 --- a/src/tools/clippy/clippy_lints/src/types/mod.rs +++ b/src/tools/clippy/clippy_lints/src/types/mod.rs @@ -260,7 +260,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(hir::Impl { of_trait: Some(_), .. }) = item.kind { @@ -815,7 +815,6 @@ impl<'tcx> LateLintPass<'tcx> for TypeComplexity { _: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, _: &'tcx Body<'_>, - _: Span, _: HirId, ) { self.check_fndecl(cx, decl); diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs index 8e076397c119a..f44a5c6af3323 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; 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, ) { // Abort if public function/method or closure. @@ -150,6 +148,7 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryWraps { ) }; + let span = cx.tcx.hir().span(hir_id); span_lint_and_then(cx, UNNECESSARY_WRAPS, span, lint_msg.as_str(), |diag| { diag.span_suggestion( fn_decl.output.span(), diff --git a/src/tools/clippy/clippy_lints/src/unwrap.rs b/src/tools/clippy/clippy_lints/src/unwrap.rs index 2fb0463c5a6c2..988148aec0bef 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap.rs @@ -9,7 +9,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! { @@ -216,9 +215,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; } @@ -228,6 +227,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_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index d81b89dd001ce..10412573d8599 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -649,7 +649,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; } From 9c1039a63e155e727caa2f1b0c4e9b6af421c206 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 7 Jun 2020 12:33:40 +0200 Subject: [PATCH 05/41] Pass HirId in save_analysis. --- .../rustc_save_analysis/src/dump_visitor.rs | 82 ++++++++++--------- compiler/rustc_save_analysis/src/lib.rs | 13 ++- 2 files changed, 55 insertions(+), 40 deletions(-) diff --git a/compiler/rustc_save_analysis/src/dump_visitor.rs b/compiler/rustc_save_analysis/src/dump_visitor.rs index a09b7e118568d..6eea8ee9026c9 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(item.def_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(item.def_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!("::{}", self.tcx.def_path_str(item.def_id.to_def_id())); @@ -537,7 +537,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()); @@ -627,12 +627,13 @@ impl<'tcx> DumpVisitor<'tcx> { fn process_impl(&mut self, item: &'tcx hir::Item<'tcx>, impl_: &'tcx hir::Impl<'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); } } } @@ -735,7 +736,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); } } @@ -801,8 +802,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); } @@ -826,10 +827,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); } } @@ -953,7 +955,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(); @@ -990,8 +994,9 @@ 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 trait_item_span = self.tcx.hir().span(trait_item.hir_id()); + let vis_span = trait_item_span.shrink_to_lo(); match trait_item.kind { hir::TraitItemKind::Const(ref ty, body) => { let body = body.map(|b| &self.tcx.hir().body(b).value); @@ -1018,7 +1023,7 @@ impl<'tcx> DumpVisitor<'tcx> { trait_item.ident, &trait_item.generics, &respan, - trait_item.span, + trait_item_span, ); } hir::TraitItemKind::Type(ref bounds, ref default_ty) => { @@ -1040,7 +1045,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, @@ -1065,7 +1070,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); @@ -1088,7 +1093,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) => { @@ -1106,7 +1111,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 @@ -1115,7 +1122,6 @@ impl<'tcx> DumpVisitor<'tcx> { .iter() .map(|i| id_from_def_id(i.def_id.to_def_id())) .collect(); - let span = self.span_from_span(krate.item.span); let attrs = self.tcx.hir().attrs(id); self.dumper.dump_def( @@ -1158,7 +1164,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; @@ -1190,8 +1196,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 = @@ -1318,10 +1325,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; } @@ -1357,7 +1364,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); @@ -1378,8 +1385,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); } } @@ -1418,7 +1426,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); } @@ -1435,12 +1443,12 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { } 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). @@ -1454,7 +1462,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); @@ -1470,7 +1478,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); } @@ -1478,7 +1486,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 042f3183796d3..16961eff39266 100644 --- a/compiler/rustc_save_analysis/src/lib.rs +++ b/compiler/rustc_save_analysis/src/lib.rs @@ -307,8 +307,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), @@ -899,7 +904,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 From 7b5f1a3aba71254baa27a7c5963f918d58ae65f6 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Wed, 3 Jun 2020 13:30:31 +0200 Subject: [PATCH 06/41] Remove Span parameter from HIR collector. --- .../rustc_middle/src/hir/map/collector.rs | 62 +++++++++---------- 1 file changed, 29 insertions(+), 33 deletions(-) diff --git a/compiler/rustc_middle/src/hir/map/collector.rs b/compiler/rustc_middle/src/hir/map/collector.rs index 00b29d6efd31d..7aa880d8874e1 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; @@ -232,11 +232,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 @@ -248,6 +248,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { None => format!("{:?}", node), }; + let span = self.krate.spans[hir_id]; span_bug!( span, "inconsistent DepNode at `{:?}` for `{}`: \ @@ -329,7 +330,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); }); @@ -339,12 +340,12 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { debug!("visit_item: {:?}", i); self.with_dep_node_owner(i.def_id, i, |this, hash| { let hir_id = i.hir_id(); - this.insert_with_hash(i.span, hir_id, Node::Item(i), hash); + this.insert_with_hash(hir_id, Node::Item(i), hash); this.with_parent(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); @@ -354,7 +355,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { fn visit_foreign_item(&mut self, fi: &'hir ForeignItem<'hir>) { self.with_dep_node_owner(fi.def_id, 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); @@ -373,21 +374,21 @@ 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); } } fn visit_trait_item(&mut self, ti: &'hir TraitItem<'hir>) { self.with_dep_node_owner(ti.def_id, 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); @@ -397,7 +398,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { fn visit_impl_item(&mut self, ii: &'hir ImplItem<'hir>) { self.with_dep_node_owner(ii.def_id, 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); @@ -408,7 +409,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); @@ -418,7 +419,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); @@ -426,7 +427,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); @@ -434,7 +435,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); @@ -442,7 +443,7 @@ 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); @@ -451,13 +452,13 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { fn visit_path_segment(&mut self, path_segment: &'hir PathSegment<'hir>) { if let Some(hir_id) = path_segment.hir_id { - self.insert(DUMMY_SP, hir_id, Node::PathSegment(path_segment)); + self.insert(hir_id, Node::PathSegment(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); @@ -465,7 +466,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); @@ -484,26 +485,26 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { } 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); }); @@ -521,29 +522,24 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { }); self.with_parent(parent, |this| { this.with_dep_node_owner(macro_def.def_id, 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); }); From 07e9c5c37414d36a0cd5a91f39be4214bf0aaac7 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 13 Dec 2020 15:32:45 +0100 Subject: [PATCH 07/41] Fix fulldeps tests. --- src/test/ui-fulldeps/auxiliary/issue-40001-plugin.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/ui-fulldeps/auxiliary/issue-40001-plugin.rs b/src/test/ui-fulldeps/auxiliary/issue-40001-plugin.rs index 124dd670d0931..1dce3eec15200 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 !cx.tcx.hir().attrs(item.hir_id()).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() }); } From 4cff471bd2daffe99c717513776830d98a3d6171 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 13 Dec 2020 19:43:06 +0100 Subject: [PATCH 08/41] Fix clippy. --- src/tools/clippy/clippy_lints/src/functions.rs | 2 +- src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs | 2 +- src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs | 2 +- src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/tools/clippy/clippy_lints/src/functions.rs b/src/tools/clippy/clippy_lints/src/functions.rs index 48e7a5f64d9cb..3eefae05f30e2 100644 --- a/src/tools/clippy/clippy_lints/src/functions.rs +++ b/src/tools/clippy/clippy_lints/src/functions.rs @@ -255,7 +255,7 @@ impl<'tcx> LateLintPass<'tcx> for Functions { intravisit::FnKind::Closure => return, }; - let span = cx.tcx.hir().span(hir_id); + 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) { 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 d01555941c682..8dc114d84fb5f 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 @@ -100,7 +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(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/panic_in_result_fn.rs b/src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs index bab0eee52833b..9cf6ffe90f447 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 @@ -43,7 +43,7 @@ impl<'tcx> LateLintPass<'tcx> for PanicInResultFn { 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(hir_id); + 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/unnecessary_wraps.rs b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs index f44a5c6af3323..121dc66963431 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs @@ -148,7 +148,7 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryWraps { ) }; - let span = cx.tcx.hir().span(hir_id); + let span = cx.tcx.hir().span_with_body(hir_id); span_lint_and_then(cx, UNNECESSARY_WRAPS, span, lint_msg.as_str(), |diag| { diag.span_suggestion( fn_decl.output.span(), From 173048da13bbdb4855415b6ce9036134a536cc97 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Fri, 1 May 2020 23:59:40 +0200 Subject: [PATCH 09/41] Remove span from hir::Param. --- compiler/rustc_ast_lowering/src/expr.rs | 2 +- compiler/rustc_ast_lowering/src/item.rs | 2 -- compiler/rustc_hir/src/hir.rs | 1 - compiler/rustc_mir_build/src/build/mod.rs | 3 ++- compiler/rustc_passes/src/check_attr.rs | 7 ++++++- compiler/rustc_typeck/src/check/check.rs | 2 +- compiler/rustc_typeck/src/check/fn_ctxt/checks.rs | 3 ++- compiler/rustc_typeck/src/check/pat.rs | 5 +++-- src/tools/clippy/clippy_lints/src/unused_self.rs | 2 +- 9 files changed, 16 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 91feff6a29bdf..50de46066558f 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -671,7 +671,7 @@ impl<'hir> LoweringContext<'_, 'hir> { Ident::with_dummy_span(sym::_task_context), hir::BindingAnnotation::Mutable, ); - let param = hir::Param { hir_id: self.next_id(span), pat, ty_span: span, span }; + let param = hir::Param { hir_id: self.next_id(span), pat, ty_span: span }; let params = arena_vec![self; param]; let body_id = self.lower_body(move |this| { diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index ec31d346a6a7a..945a260805f91 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1042,7 +1042,6 @@ impl<'hir> LoweringContext<'_, 'hir> { hir_id, pat: self.lower_pat(¶m.pat), ty_span: param.ty.span, - span: param.span, } } @@ -1177,7 +1176,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 { diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index d0a9f3b4ca59a..d58d404d27b07 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2425,7 +2425,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. diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index 9c83c0d09aa8e..a6229a66587ad 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -156,7 +156,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 { diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index c7b266f18bf8d..4c341efdeb960 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1290,7 +1290,12 @@ impl Visitor<'tcx> for CheckAttrVisitor<'tcx> { } fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { - self.check_attributes(param.hir_id, ¶m.span, Target::Param, None); + self.check_attributes( + param.hir_id, + &self.tcx.hir().span(param.hir_id), + Target::Param, + None, + ); intravisit::walk_param(self, param); } diff --git a/compiler/rustc_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index 0010d59f710cd..3aa1a51964135 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -160,7 +160,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)); diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs index 5b8b25c210018..2f551aa03ffda 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs @@ -185,7 +185,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .flatten(); for param in 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()); } let def_kind = tcx.def_kind(def_id); diff --git a/compiler/rustc_typeck/src/check/pat.rs b/compiler/rustc_typeck/src/check/pat.rs index f8ca916caf127..ac39bef590a5c 100644 --- a/compiler/rustc_typeck/src/check/pat.rs +++ b/compiler/rustc_typeck/src/check/pat.rs @@ -624,10 +624,11 @@ 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, .. }) => { + hir::Node::Param(hir::Param { hir_id, .. }) => { + let span = tcx.hir().span(*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, diff --git a/src/tools/clippy/clippy_lints/src/unused_self.rs b/src/tools/clippy/clippy_lints/src/unused_self.rs index 812482cf5cfb6..bb705b7c78c3d 100644 --- a/src/tools/clippy/clippy_lints/src/unused_self.rs +++ b/src/tools/clippy/clippy_lints/src/unused_self.rs @@ -58,7 +58,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", From 56a6530c133b0e0fea19ec6edfd4a91511401881 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 May 2020 00:52:01 +0200 Subject: [PATCH 10/41] Remove span from hir::Variant. --- compiler/rustc_ast_lowering/src/item.rs | 1 - compiler/rustc_hir/src/hir.rs | 2 -- compiler/rustc_hir_pretty/src/lib.rs | 21 +++++++++++++------ compiler/rustc_lint/src/builtin.rs | 3 ++- compiler/rustc_lint/src/types.rs | 19 +++++++---------- compiler/rustc_passes/src/check_attr.rs | 3 ++- compiler/rustc_passes/src/dead.rs | 3 ++- compiler/rustc_passes/src/stability.rs | 8 ++++--- compiler/rustc_typeck/src/check/check.rs | 8 +++---- compiler/rustc_typeck/src/collect.rs | 8 +++---- src/librustdoc/doctest.rs | 3 ++- .../clippy/clippy_lints/src/enum_clike.rs | 2 +- .../clippy_lints/src/large_enum_variant.rs | 8 +++---- .../clippy/clippy_lints/src/missing_doc.rs | 3 ++- 14 files changed, 50 insertions(+), 42 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 945a260805f91..e0e24ae57ce9e 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -756,7 +756,6 @@ impl<'hir> LoweringContext<'_, 'hir> { data: self.lower_variant_data(id, &v.data), disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)), ident: v.ident, - span: v.span, } } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index d58d404d27b07..585460ad130db 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2544,8 +2544,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)] diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 9c2766a16318d..c7f76ab9cd0b8 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}; @@ -85,6 +85,7 @@ pub struct State<'a> { comments: Option>, attrs: &'a BTreeMap, ann: &'a (dyn PpAnn + 'a), + spans: &'a HirIdVec, } impl<'a> State<'a> { @@ -165,7 +166,7 @@ pub fn print_crate<'a>( input: String, ann: &'a dyn PpAnn, ) -> String { - let mut s = State::new_from_input(sm, filename, input, &krate.attrs, ann); + let mut s = State::new_from_input(sm, filename, input, &krate.attrs, &krate.spans, ann); // When printing the AST, we sometimes need to inject `#[no_std]` here. // Since you can't compile the HIR, it's not necessary. @@ -181,12 +182,14 @@ impl<'a> State<'a> { filename: FileName, input: String, attrs: &'a BTreeMap, + spans: &'a HirIdVec, ann: &'a dyn PpAnn, ) -> State<'a> { State { s: pp::mk_printer(), comments: Some(Comments::new(sm, filename, input)), attrs, + spans, ann, } } @@ -194,14 +197,19 @@ impl<'a> State<'a> { fn attrs(&self, id: hir::HirId) -> &'a [ast::Attribute] { self.attrs.get(&id).map_or(&[], |la| *la) } + + fn span(&self, hir_id: hir::HirId) -> rustc_span::Span { + self.spans.get(hir_id).copied().unwrap_or(rustc_span::DUMMY_SP) + } } pub fn to_string(ann: &dyn PpAnn, f: F) -> String where F: FnOnce(&mut State<'_>), { + let spans = &HirIdVec::default(); let mut printer = - State { s: pp::mk_printer(), comments: None, attrs: &BTreeMap::default(), ann }; + State { s: pp::mk_printer(), comments: None, attrs: &BTreeMap::default(), spans, ann }; f(&mut printer); printer.s.eof() } @@ -834,14 +842,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(self.attrs(v.id)); 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) } @@ -928,7 +937,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("="); diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index a6c31c53051d8..af993876c80e4 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -658,7 +658,8 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { } fn check_variant(&mut self, cx: &LateContext<'_>, v: &hir::Variant<'_>) { - self.check_missing_docs_attrs(cx, v.id, v.span, "a", "variant"); + let span = cx.tcx.hir().span(v.id); + self.check_missing_docs_attrs(cx, v.id, span, "a", "variant"); } } diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 5fcc087701523..55662ee9c1522 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1379,18 +1379,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_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 4c341efdeb960..43bf639bda189 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1280,7 +1280,8 @@ impl Visitor<'tcx> for CheckAttrVisitor<'tcx> { generics: &'tcx hir::Generics<'tcx>, item_id: HirId, ) { - self.check_attributes(variant.id, &variant.span, Target::Variant, None); + let span = self.tcx.hir().span(variant.id); + self.check_attributes(variant.id, &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 acce8e785a332..42396693636e8 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -636,7 +636,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); } diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 3e957aabd7763..0b70d93c9e39e 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -440,9 +440,10 @@ 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.span, + var_span, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -451,7 +452,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { if let Some(ctor_hir_id) = var.data.ctor_hir_id() { v.annotate( ctor_hir_id, - var.span, + var_span, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -606,7 +607,8 @@ 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); } diff --git a/compiler/rustc_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index 3aa1a51964135..ba6aa991eb524 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -1420,10 +1420,10 @@ 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/collect.rs b/compiler/rustc_typeck/src/collect.rs index a175da3270638..053edbf3dd30d 100644 --- a/compiler/rustc_typeck/src/collect.rs +++ b/compiler/rustc_typeck/src/collect.rs @@ -890,11 +890,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 diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 64375964e7068..39dc614afe0b1 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -1083,7 +1083,8 @@ 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.id, v.span, |this| { + let span = self.map.span(v.id); + self.visit_testable(v.ident.to_string(), v.id, span, |this| { intravisit::walk_variant(this, v, g, item_id); }); } diff --git a/src/tools/clippy/clippy_lints/src/enum_clike.rs b/src/tools/clippy/clippy_lints/src/enum_clike.rs index aa235642ac310..e08de27c1a0b4 100644 --- a/src/tools/clippy/clippy_lints/src/enum_clike.rs +++ b/src/tools/clippy/clippy_lints/src/enum_clike.rs @@ -70,7 +70,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/large_enum_variant.rs b/src/tools/clippy/clippy_lints/src/large_enum_variant.rs index ab4cb33612d38..c76490c69ded1 100644 --- a/src/tools/clippy/clippy_lints/src/large_enum_variant.rs +++ b/src/tools/clippy/clippy_lints/src/large_enum_variant.rs @@ -99,15 +99,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 { @@ -127,7 +127,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/missing_doc.rs b/src/tools/clippy/clippy_lints/src/missing_doc.rs index 6ec4c38d0f9cc..3872298920988 100644 --- a/src/tools/clippy/clippy_lints/src/missing_doc.rs +++ b/src/tools/clippy/clippy_lints/src/missing_doc.rs @@ -197,6 +197,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { fn check_variant(&mut self, cx: &LateContext<'tcx>, v: &'tcx hir::Variant<'_>) { let attrs = cx.tcx.hir().attrs(v.id); - self.check_missing_docs_attrs(cx, attrs, v.span, "a", "variant"); + let span = cx.tcx.hir().span(v.id); + self.check_missing_docs_attrs(cx, attrs, span, "a", "variant"); } } From 272a1f25449ee718274ff2322c3f59c29f52f13d Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 May 2020 01:04:23 +0200 Subject: [PATCH 11/41] Remove span from hir::StructField. --- compiler/rustc_ast_lowering/src/item.rs | 7 +------ compiler/rustc_hir/src/hir.rs | 1 - compiler/rustc_hir_pretty/src/lib.rs | 6 ++++-- compiler/rustc_lint/src/builtin.rs | 9 ++++++--- compiler/rustc_passes/src/check_attr.rs | 3 ++- compiler/rustc_passes/src/dead.rs | 3 ++- compiler/rustc_passes/src/stability.rs | 6 ++++-- compiler/rustc_typeck/src/collect.rs | 5 +++-- src/librustdoc/doctest.rs | 3 ++- src/tools/clippy/clippy_lints/src/missing_doc.rs | 3 ++- 10 files changed, 26 insertions(+), 20 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index e0e24ae57ce9e..4b4a850226105 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -804,7 +804,6 @@ impl<'hir> LoweringContext<'_, 'hir> { let hir_id = self.lower_node_id(f.id, f.span); self.lower_attrs(hir_id, &f.attrs); hir::StructField { - span: f.span, hir_id, ident: match f.ident { Some(ident) => ident, @@ -1037,11 +1036,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> { let hir_id = self.lower_node_id(param.id, param.span); self.lower_attrs(hir_id, ¶m.attrs); - hir::Param { - hir_id, - pat: self.lower_pat(¶m.pat), - ty_span: param.ty.span, - } + hir::Param { hir_id, pat: self.lower_pat(¶m.pat), ty_span: param.ty.span } } pub(super) fn lower_fn_body( diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 585460ad130db..3f5eea195ad8c 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2623,7 +2623,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>, diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index c7f76ab9cd0b8..1a9733c29828f 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -898,7 +898,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(s.attrs(field.hir_id)); s.print_visibility(&field.vis); s.print_type(&field.ty) @@ -919,8 +920,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(self.attrs(field.hir_id)); self.print_visibility(&field.vis); self.print_ident(field.ident); diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index af993876c80e4..6853473569e26 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -183,7 +183,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)); } } _ => (), @@ -653,7 +654,8 @@ 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, sf.hir_id, sf.span, "a", "struct field") + let span = cx.tcx.hir().span(sf.hir_id); + self.check_missing_docs_attrs(cx, sf.hir_id, span, "a", "struct field") } } @@ -1347,7 +1349,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<'_>) { diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 43bf639bda189..651ee1dce050f 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1230,7 +1230,8 @@ impl Visitor<'tcx> for CheckAttrVisitor<'tcx> { } fn visit_struct_field(&mut self, struct_field: &'tcx hir::StructField<'tcx>) { - self.check_attributes(struct_field.hir_id, &struct_field.span, Target::Field, None); + let span = self.tcx.hir().span(struct_field.hir_id); + self.check_attributes(struct_field.hir_id, &span, Target::Field, None); intravisit::walk_struct_field(self, struct_field); } diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 42396693636e8..4de5f11315742 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -652,7 +652,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/stability.rs b/compiler/rustc_passes/src/stability.rs index 0b70d93c9e39e..1f578ea372ef1 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -467,9 +467,10 @@ 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.span, + span, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -613,7 +614,8 @@ impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> { } 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); } diff --git a/compiler/rustc_typeck/src/collect.rs b/compiler/rustc_typeck/src/collect.rs index 053edbf3dd30d..68722c5a10afb 100644 --- a/compiler/rustc_typeck/src/collect.rs +++ b/compiler/rustc_typeck/src/collect.rs @@ -934,15 +934,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) } diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 39dc614afe0b1..4832b6f08728a 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -1090,7 +1090,8 @@ impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> } fn visit_struct_field(&mut self, f: &'hir hir::StructField<'_>) { - self.visit_testable(f.ident.to_string(), f.hir_id, f.span, |this| { + let span = self.map.span(f.hir_id); + self.visit_testable(f.ident.to_string(), f.hir_id, span, |this| { intravisit::walk_struct_field(this, f); }); } diff --git a/src/tools/clippy/clippy_lints/src/missing_doc.rs b/src/tools/clippy/clippy_lints/src/missing_doc.rs index 3872298920988..3a4c5b496da7f 100644 --- a/src/tools/clippy/clippy_lints/src/missing_doc.rs +++ b/src/tools/clippy/clippy_lints/src/missing_doc.rs @@ -191,7 +191,8 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { fn check_struct_field(&mut self, cx: &LateContext<'tcx>, sf: &'tcx hir::StructField<'_>) { if !sf.is_positional() { let attrs = cx.tcx.hir().attrs(sf.hir_id); - self.check_missing_docs_attrs(cx, attrs, sf.span, "a", "struct field"); + let span = cx.tcx.hir().span(sf.hir_id); + self.check_missing_docs_attrs(cx, attrs, span, "a", "struct field"); } } From 7b8595fad289e0f57e819085bcb0c8694517ed8f Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 6 Mar 2021 20:05:27 +0100 Subject: [PATCH 12/41] Remove span from hir::Stmt. --- compiler/rustc_ast_lowering/src/lib.rs | 14 ++++---------- compiler/rustc_hir/src/hir.rs | 1 - compiler/rustc_hir_pretty/src/lib.rs | 5 +++-- compiler/rustc_lint/src/unused.rs | 14 ++++++++------ compiler/rustc_middle/src/middle/region.rs | 2 +- compiler/rustc_passes/src/check_attr.rs | 3 ++- compiler/rustc_passes/src/naked_functions.rs | 4 ++-- .../src/traits/error_reporting/suggestions.rs | 3 ++- compiler/rustc_typeck/src/check/_match.rs | 3 ++- compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs | 3 ++- compiler/rustc_typeck/src/check/fn_ctxt/checks.rs | 5 +++-- .../clippy_lints/src/blocks_in_if_conditions.rs | 2 +- src/tools/clippy/clippy_lints/src/default.rs | 3 ++- src/tools/clippy/clippy_lints/src/eq_op.rs | 3 ++- src/tools/clippy/clippy_lints/src/let_if_seq.rs | 2 +- .../clippy_lints/src/loops/needless_collect.rs | 5 +++-- .../clippy_lints/src/loops/single_element_loop.rs | 2 +- src/tools/clippy/clippy_lints/src/macro_use.rs | 5 +++-- src/tools/clippy/clippy_lints/src/map_unit_fn.rs | 11 ++++++----- src/tools/clippy/clippy_lints/src/matches.rs | 7 ++++--- src/tools/clippy/clippy_lints/src/misc.rs | 10 ++++++---- src/tools/clippy/clippy_lints/src/no_effect.rs | 4 ++-- src/tools/clippy/clippy_lints/src/returns.rs | 3 ++- src/tools/clippy/clippy_lints/src/swap.rs | 2 +- src/tools/clippy/clippy_lints/src/types/mod.rs | 9 +++++---- .../clippy_lints/src/unit_return_expecting_ord.rs | 2 +- .../clippy/clippy_lints/src/vec_init_then_push.rs | 3 ++- 27 files changed, 71 insertions(+), 59 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index d81a76c399fa4..94b6c1582e8bc 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -2483,13 +2483,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { .collect(); let hir_id = self.lower_node_id(s.id, s.span); self.alias_attrs(hir_id, l.hir_id); - ids.push({ - hir::Stmt { - hir_id, - kind: hir::StmtKind::Local(self.arena.alloc(l)), - span: s.span, - } - }); + ids.push(hir::Stmt { hir_id, kind: hir::StmtKind::Local(self.arena.alloc(l)) }); return ids; } StmtKind::Item(ref it) => { @@ -2504,7 +2498,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { .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(); } @@ -2523,7 +2517,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { StmtKind::Empty => return smallvec![], StmtKind::MacCall(..) => panic!("shouldn't exist here"), }; - smallvec![hir::Stmt { hir_id, kind, span: s.span }] + smallvec![hir::Stmt { hir_id, kind }] } fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode { @@ -2558,7 +2552,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(span) } + hir::Stmt { kind, hir_id: self.next_id(span) } } fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> { diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 3f5eea195ad8c..2789ed9883fa2 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1151,7 +1151,6 @@ impl UnOp { pub struct Stmt<'hir> { pub hir_id: HirId, pub kind: StmtKind<'hir>, - pub span: Span, } /// The contents of a statement. diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 1a9733c29828f..9a4fe6ba846e9 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -1041,7 +1041,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)); @@ -1060,7 +1061,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<'_>) { diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 67946dfb292a6..bd345421e669f 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_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_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 651ee1dce050f..c6b6fe6883489 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1260,7 +1260,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, &stmt.span, Target::Statement, None); + let stmt_span = self.tcx.hir().span(stmt.hir_id); + self.check_attributes(l.hir_id, &stmt_span, Target::Statement, None); } intravisit::walk_stmt(self, stmt) } diff --git a/compiler/rustc_passes/src/naked_functions.rs b/compiler/rustc_passes/src/naked_functions.rs index 5e38ffbb41eeb..a20e6b4cdbeac 100644 --- a/compiler/rustc_passes/src/naked_functions.rs +++ b/compiler/rustc_passes/src/naked_functions.rs @@ -310,10 +310,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_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index c1b105f1d8489..65524df385f16 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -920,7 +920,8 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { // Once that is added, close #54771. if let Some(ref stmt) = blk.stmts.last() { if let hir::StmtKind::Semi(_) = stmt.kind { - let sp = self.tcx.sess.source_map().end_point(stmt.span); + let stmt_span = self.tcx.hir().span(stmt.hir_id); + let sp = self.tcx.sess.source_map().end_point(stmt_span); err.span_label(sp, "consider removing this semicolon"); } } diff --git a/compiler/rustc_typeck/src/check/_match.rs b/compiler/rustc_typeck/src/check/_match.rs index d056f2c90f988..1cfc9eedd6f8d 100644 --- a/compiler/rustc_typeck/src/check/_match.rs +++ b/compiler/rustc_typeck/src/check/_match.rs @@ -577,8 +577,9 @@ 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) diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs index f5e9cc1efcc45..220a80fb08228 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs @@ -1136,7 +1136,8 @@ 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 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 2f551aa03ffda..def7e18759331 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs @@ -547,7 +547,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); @@ -572,7 +573,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // in order to capture the fact that this `match` is the last statement in its // function. This is done for better suggestions to remove the `;`. let expectation = match expr.kind { - hir::ExprKind::Match(..) if is_last => IsLast(stmt.span), + hir::ExprKind::Match(..) if is_last => IsLast(self.tcx.hir().span(stmt.hir_id)), _ => NoExpectation, }; self.check_expr_with_expectation(expr, expectation); 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 b53f80fd8bc15..7ae998676755e 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 @@ -122,7 +122,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; } diff --git a/src/tools/clippy/clippy_lints/src/default.rs b/src/tools/clippy/clippy_lints/src/default.rs index 6fa1378b8c73d..b0cd8297c8bbe 100644 --- a/src/tools/clippy/clippy_lints/src/default.rs +++ b/src/tools/clippy/clippy_lints/src/default.rs @@ -209,10 +209,11 @@ 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); 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), &format!( 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/let_if_seq.rs b/src/tools/clippy/clippy_lints/src/let_if_seq.rs index 5863eef8a26f8..0e1f526b1c59e 100644 --- a/src/tools/clippy/clippy_lints/src/let_if_seq.rs +++ b/src/tools/clippy/clippy_lints/src/let_if_seq.rs @@ -69,7 +69,7 @@ impl<'tcx> LateLintPass<'tcx> for LetIfSeq { if let Some(value) = check_assign(cx, canonical_id, &*then); if !used_visitor.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/loops/needless_collect.rs b/src/tools/clippy/clippy_lints/src/loops/needless_collect.rs index 92560c806295c..563ed6ff01d67 100644 --- a/src/tools/clippy/clippy_lints/src/loops/needless_collect.rs +++ b/src/tools/clippy/clippy_lints/src/loops/needless_collect.rs @@ -116,17 +116,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, super::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/loops/single_element_loop.rs b/src/tools/clippy/clippy_lints/src/loops/single_element_loop.rs index 38400c93c9ab2..649bc633fa200 100644 --- a/src/tools/clippy/clippy_lints/src/loops/single_element_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/single_element_loop.rs @@ -34,7 +34,7 @@ pub(super) fn check<'tcx>( 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, cx.tcx.hir().span(block.stmts[0].hir_id)).unwrap_or(0)), target.name, list_item_name, block_str), Applicability::MachineApplicable ) } diff --git a/src/tools/clippy/clippy_lints/src/macro_use.rs b/src/tools/clippy/clippy_lints/src/macro_use.rs index 6d9c78393c8c4..056ee195ce11c 100644 --- a/src/tools/clippy/clippy_lints/src/macro_use.rs +++ b/src/tools/clippy/clippy_lints/src/macro_use.rs @@ -138,8 +138,9 @@ 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<'_>) { 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 01126e86199b4..c5548e3580cd6 100644 --- a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs +++ b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs @@ -143,7 +143,7 @@ fn reduce_unit_expression<'a>(cx: &LateContext<'_>, expr: &'a hir::Expr<'_>) -> match inner_stmt.kind { hir::StmtKind::Local(ref local) => Some(local.span), 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); @@ -242,7 +243,7 @@ fn lint_map_unit_fn(cx: &LateContext<'_>, stmt: &hir::Stmt<'_>, expr: &hir::Expr snippet(cx, reduced_expr_span, "_") ); diag.span_suggestion( - stmt.span, + stmt_span, "try this", suggestion, Applicability::MachineApplicable, // snippet @@ -254,7 +255,7 @@ fn lint_map_unit_fn(cx: &LateContext<'_>, stmt: &hir::Stmt<'_>, expr: &hir::Expr snippet(cx, binding.pat.span, "_"), 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 1d5a6e7fcc53c..a7e1907b6d127 100644 --- a/src/tools/clippy/clippy_lints/src/matches.rs +++ b/src/tools/clippy/clippy_lints/src/matches.rs @@ -936,7 +936,7 @@ fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, 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, @@ -1065,13 +1065,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, } diff --git a/src/tools/clippy/clippy_lints/src/misc.rs b/src/tools/clippy/clippy_lints/src/misc.rs index 2310facef33c4..69ebab6e3a783 100644 --- a/src/tools/clippy/clippy_lints/src/misc.rs +++ b/src/tools/clippy/clippy_lints/src/misc.rs @@ -301,7 +301,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; @@ -333,7 +334,7 @@ impl<'tcx> LateLintPass<'tcx> for MiscLints { "`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};", @@ -354,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/no_effect.rs b/src/tools/clippy/clippy_lints/src/no_effect.rs index 69302d695ce0a..7202f2e4c525c 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/returns.rs b/src/tools/clippy/clippy_lints/src/returns.rs index e1ae4aec8b915..8c3c984f71062 100644 --- a/src/tools/clippy/clippy_lints/src/returns.rs +++ b/src/tools/clippy/clippy_lints/src/returns.rs @@ -159,7 +159,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/swap.rs b/src/tools/clippy/clippy_lints/src/swap.rs index 9d8a0c248334f..c91640a2c807d 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/mod.rs b/src/tools/clippy/clippy_lints/src/types/mod.rs index 5dc1f1c245d19..40a85953aaf60 100644 --- a/src/tools/clippy/clippy_lints/src/types/mod.rs +++ b/src/tools/clippy/clippy_lints/src/types/mod.rs @@ -415,7 +415,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) || local.pat.span.from_expansion() { return; } if higher::is_from_for_desugar(local) { @@ -424,13 +425,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 @@ -676,7 +677,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, )) } 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 c6ae8b9b59837..acead29fdfe27 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/vec_init_then_push.rs b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs index 8d111f98add9a..30b96a7d0ad32 100644 --- a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs +++ b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs @@ -134,10 +134,11 @@ impl LateLintPass<'_> for VecInitThenPush { if let ExprKind::MethodCall(path, _, [self_arg, _], _) = expr.kind; if path_to_local_id(self_arg, searcher.local_id); if path.ident.name.as_str() == "push"; + let stmt_span = cx.tcx.hir().span(stmt.hir_id); then { self.searcher = Some(VecPushSearcher { found: searcher.found + 1, - err_span: searcher.err_span.to(stmt.span), + err_span: searcher.err_span.to(stmt_span), .. searcher }); } else { From a295ae30c5312053c043c60e9934bcdd1876030c Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 May 2020 01:37:49 +0200 Subject: [PATCH 13/41] Remove span from hir::Block. --- compiler/rustc_ast_lowering/src/expr.rs | 4 ++-- compiler/rustc_ast_lowering/src/lib.rs | 3 +-- compiler/rustc_hir/src/hir.rs | 3 +-- compiler/rustc_hir_pretty/src/lib.rs | 7 ++++--- compiler/rustc_mir_build/src/thir/cx/block.rs | 2 +- compiler/rustc_passes/src/loops.rs | 3 ++- compiler/rustc_typeck/src/check/_match.rs | 3 ++- compiler/rustc_typeck/src/check/expr.rs | 6 ++++-- .../rustc_typeck/src/check/fn_ctxt/_impl.rs | 3 ++- .../rustc_typeck/src/check/fn_ctxt/checks.rs | 20 +++++++++++-------- compiler/rustc_typeck/src/check/writeback.rs | 3 ++- .../src/blocks_in_if_conditions.rs | 2 +- src/tools/clippy/clippy_lints/src/copies.rs | 4 ++-- .../src/loops/single_element_loop.rs | 2 +- .../clippy_lints/src/manual_async_fn.rs | 5 +++-- src/tools/clippy/clippy_lints/src/matches.rs | 3 ++- .../src/semicolon_if_nothing_returned.rs | 2 +- .../clippy/clippy_utils/src/hir_utils.rs | 9 +++++---- 18 files changed, 48 insertions(+), 36 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 50de46066558f..83552f44850e6 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -2130,7 +2130,6 @@ impl<'hir> LoweringContext<'_, 'hir> { expr: Some(expr), hir_id, rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated), - span, targeted_by_break: false, }), None, @@ -2150,7 +2149,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( diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 94b6c1582e8bc..7575e005a1dd1 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -2449,7 +2449,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let rules = self.lower_block_check_mode(&b.rules); 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 @@ -2591,7 +2591,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { expr, hir_id: self.next_id(span), rules: hir::BlockCheckMode::DefaultBlock, - span, targeted_by_break: false, }; self.arena.alloc(blk) diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 2789ed9883fa2..2f6239afe98c2 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -797,7 +797,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. @@ -3068,7 +3067,7 @@ impl<'hir> Node<'hir> { // Some nodes are used a lot. Make sure they don't unintentionally get bigger. #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] mod size_asserts { - rustc_data_structures::static_assert_size!(super::Block<'static>, 48); + rustc_data_structures::static_assert_size!(super::Block<'static>, 40); rustc_data_structures::static_assert_size!(super::Expr<'static>, 64); rustc_data_structures::static_assert_size!(super::Pat<'static>, 88); rustc_data_structures::static_assert_size!(super::QPath<'static>, 24); diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 9a4fe6ba846e9..8592c1fe24bd9 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -1088,7 +1088,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(); @@ -1100,9 +1101,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)) } diff --git a/compiler/rustc_mir_build/src/thir/cx/block.rs b/compiler/rustc_mir_build/src/thir/cx/block.rs index d450f8a265d99..9bf1e5cdd630e 100644 --- a/compiler/rustc_mir_build/src/thir/cx/block.rs +++ b/compiler/rustc_mir_build/src/thir/cx/block.rs @@ -21,7 +21,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { data: region::ScopeData::Node, }, opt_destruction_scope, - span: block.span, + span: self.tcx.hir().span(block.hir_id), stmts, expr: block.expr.map(|expr| self.mirror_expr(expr)), safety_mode: match block.rules { diff --git a/compiler/rustc_passes/src/loops.rs b/compiler/rustc_passes/src/loops.rs index 4bfac1b72983e..5122368779768 100644 --- a/compiler/rustc_passes/src/loops.rs +++ b/compiler/rustc_passes/src/loops.rs @@ -184,6 +184,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, @@ -191,7 +192,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_typeck/src/check/_match.rs b/compiler/rustc_typeck/src/check/_match.rs index 1cfc9eedd6f8d..4453f52209315 100644 --- a/compiler/rustc_typeck/src/check/_match.rs +++ b/compiler/rustc_typeck/src/check/_match.rs @@ -582,7 +582,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (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/expr.rs b/compiler/rustc_typeck/src/check/expr.rs index 48740e533da8e..a504c987e7fbf 100644 --- a/compiler/rustc_typeck/src/check/expr.rs +++ b/compiler/rustc_typeck/src/check/expr.rs @@ -889,7 +889,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)) } @@ -917,8 +918,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()) } diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs index 220a80fb08228..92f166c1deb77 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs @@ -1137,7 +1137,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return None; } let last_stmt_span = self.tcx.hir().span(last_stmt.hir_id); - let original_span = original_sp(last_stmt_span, blk.span); + 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 def7e18759331..9e07b056fed53 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs @@ -592,7 +592,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); } } @@ -620,7 +621,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 { @@ -668,7 +670,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(); @@ -676,7 +678,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); } @@ -792,7 +795,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); } } _ => {} @@ -821,12 +825,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if ty.is_never() { None } else { - Some(match elem.kind { + self.tcx.hir().opt_span(match elem.kind { // Point at the tail expression when possible. hir::ExprKind::Block(block, _) => { - block.expr.map_or(block.span, |e| e.span) + block.expr.map_or(block.hir_id, |e| e.hir_id) } - _ => elem.span, + _ => elem.hir_id, }) } }) diff --git a/compiler/rustc_typeck/src/check/writeback.rs b/compiler/rustc_typeck/src/check/writeback.rs index af82a3bb4f59a..e189375a32e3a 100644 --- a/compiler/rustc_typeck/src/check/writeback.rs +++ b/compiler/rustc_typeck/src/check/writeback.rs @@ -288,7 +288,8 @@ 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); } 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 7ae998676755e..6bbd27b0c35e2 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 @@ -138,7 +138,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/copies.rs b/src/tools/clippy/clippy_lints/src/copies.rs index 944aaafb46de5..ffa8221789804 100644 --- a/src/tools/clippy/clippy_lints/src/copies.rs +++ b/src/tools/clippy/clippy_lints/src/copies.rs @@ -136,9 +136,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/loops/single_element_loop.rs b/src/tools/clippy/clippy_lints/src/loops/single_element_loop.rs index 649bc633fa200..c57a4063d8b7f 100644 --- a/src/tools/clippy/clippy_lints/src/loops/single_element_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/single_element_loop.rs @@ -23,7 +23,7 @@ pub(super) fn check<'tcx>( then { let for_span = get_span_of_entire_for_loop(expr); - let mut block_str = snippet(cx, block.span, "..").into_owned(); + let mut block_str = snippet(cx, cx.tcx.hir().span(block.hir_id), "..").into_owned(); block_str.remove(0); block_str.pop(); 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 b2f03c47f8918..c04b4efaf7857 100644 --- a/src/tools/clippy/clippy_lints/src/manual_async_fn.rs +++ b/src/tools/clippy/clippy_lints/src/manual_async_fn.rs @@ -80,9 +80,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/matches.rs b/src/tools/clippy/clippy_lints/src/matches.rs index a7e1907b6d127..cf10abf287a8b 100644 --- a/src/tools/clippy/clippy_lints/src/matches.rs +++ b/src/tools/clippy/clippy_lints/src/matches.rs @@ -1320,7 +1320,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(';'); } }, diff --git a/src/tools/clippy/clippy_lints/src/semicolon_if_nothing_returned.rs b/src/tools/clippy/clippy_lints/src/semicolon_if_nothing_returned.rs index 839c995e52562..8bc9272691087 100644 --- a/src/tools/clippy/clippy_lints/src/semicolon_if_nothing_returned.rs +++ b/src/tools/clippy/clippy_lints/src/semicolon_if_nothing_returned.rs @@ -37,7 +37,7 @@ declare_lint_pass!(SemicolonIfNothingReturned => [SEMICOLON_IF_NOTHING_RETURNED] impl LateLintPass<'_> for SemicolonIfNothingReturned { fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx Block<'tcx>) { if_chain! { - if !in_macro(block.span); + if !in_macro(cx.tcx.hir().span(block.hir_id)); if let Some(expr) = block.expr; let t_expr = cx.typeck_results().expr_ty(expr); if t_expr.is_unit(); diff --git a/src/tools/clippy/clippy_utils/src/hir_utils.rs b/src/tools/clippy/clippy_utils/src/hir_utils.rs index e28ad27d9a6f8..f73ae9c121eba 100644 --- a/src/tools/clippy/clippy_utils/src/hir_utils.rs +++ b/src/tools/clippy/clippy_utils/src/hir_utils.rs @@ -116,8 +116,8 @@ impl HirEqInterExpr<'_, '_, '_> { // For empty blocks, check to see if the tokens are equal. This will catch the case where a macro // expanded to nothing, or the cfg attribute was used. let (left, right) = match ( - snippet_opt(self.inner.cx, left.span), - snippet_opt(self.inner.cx, right.span), + snippet_opt(self.inner.cx, self.inner.cx.tcx.hir().span(left.hir_id)), + snippet_opt(self.inner.cx, self.inner.cx.tcx.hir().span(right.hir_id)), ) { (Some(left), Some(right)) => (left, right), _ => return true, @@ -412,12 +412,13 @@ impl HirEqInterExpr<'_, '_, '_> { /// Some simple reductions like `{ return }` => `return` fn reduce_exprkind<'hir>(cx: &LateContext<'_>, kind: &'hir ExprKind<'hir>) -> &'hir ExprKind<'hir> { if let ExprKind::Block(block, _) = kind { + let block_span = cx.tcx.hir().span(block.hir_id); match (block.stmts, block.expr) { // From an `if let` expression without an `else` block. The arm for the implicit wild pattern is an empty // block with an empty span. - ([], None) if block.span.is_empty() => &ExprKind::Tup(&[]), + ([], None) if block_span.is_empty() => &ExprKind::Tup(&[]), // `{}` => `()` - ([], None) => match snippet_opt(cx, block.span) { + ([], None) => match snippet_opt(cx, block_span) { // Don't reduce if there are any tokens contained in the braces Some(snip) if tokenize(&snip) From 32716aea400e28a3e54092d941cbb07b3343d405 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 May 2020 11:09:43 +0200 Subject: [PATCH 14/41] Remove span from hir::MacroDef. --- compiler/rustc_ast_lowering/src/item.rs | 1 - compiler/rustc_hir/src/hir.rs | 1 - compiler/rustc_hir/src/stable_hash_impls.rs | 3 +-- compiler/rustc_lint/src/builtin.rs | 3 ++- compiler/rustc_passes/src/check_attr.rs | 3 ++- compiler/rustc_passes/src/stability.rs | 6 ++++-- src/librustdoc/doctest.rs | 2 +- 7 files changed, 10 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 4b4a850226105..8cd5b6db478ba 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -226,7 +226,6 @@ impl<'hir> LoweringContext<'_, 'hir> { ident, vis, def_id: hir_id.expect_owner(), - span: i.span, ast: MacroDef { body, macro_rules }, }); } else { diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 2f6239afe98c2..e145fa7e0c4c1 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -772,7 +772,6 @@ pub struct MacroDef<'hir> { pub ident: Ident, pub vis: Visibility<'hir>, pub def_id: LocalDefId, - pub span: Span, pub ast: ast::MacroDef, } diff --git a/compiler/rustc_hir/src/stable_hash_impls.rs b/compiler/rustc_hir/src/stable_hash_impls.rs index 55e87663a1ee7..ea6af8c104e6b 100644 --- a/compiler/rustc_hir/src/stable_hash_impls.rs +++ b/compiler/rustc_hir/src/stable_hash_impls.rs @@ -194,13 +194,12 @@ impl HashStable for Item<'_> { impl HashStable for MacroDef<'_> { fn hash_stable(&self, hcx: &mut HirCtx, hasher: &mut StableHasher) { - let MacroDef { ident, def_id: _, ref ast, ref vis, span } = *self; + let MacroDef { ident, def_id: _, ref ast, ref vis } = *self; hcx.hash_hir_item_like(|hcx| { ident.name.hash_stable(hcx, hasher); ast.hash_stable(hcx, hasher); vis.hash_stable(hcx, hasher); - span.hash_stable(hcx, hasher); }); } } diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 6853473569e26..9affaf3892264 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -572,9 +572,10 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { let attrs = cx.tcx.hir().attrs(macro_def.hir_id()); let has_doc = 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(), ); } diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index c6b6fe6883489..72ac776fb1d4e 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1288,7 +1288,8 @@ impl Visitor<'tcx> for CheckAttrVisitor<'tcx> { } fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) { - self.check_attributes(macro_def.hir_id(), ¯o_def.span, Target::MacroDef, None); + let span = self.tcx.hir().span(macro_def.hir_id()); + self.check_attributes(macro_def.hir_id(), &span, Target::MacroDef, None); intravisit::walk_macro_def(self, macro_def); } diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 1f578ea372ef1..4bdd5a35df1fc 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -496,9 +496,10 @@ 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.span, + span, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -625,7 +626,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, diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 4832b6f08728a..505249c4f4de6 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -1100,7 +1100,7 @@ impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> self.visit_testable( macro_def.ident.to_string(), macro_def.hir_id(), - macro_def.span, + self.map.span(macro_def.hir_id()), |_| (), ); } From 6ec23566d213ea58811d5fb7e0181dc59cb31064 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 May 2020 11:50:15 +0200 Subject: [PATCH 15/41] Remove span from hir::GenericParam. --- compiler/rustc_ast_lowering/src/lib.rs | 4 -- compiler/rustc_hir/src/hir.rs | 11 +---- .../src/infer/error_reporting/mod.rs | 4 +- compiler/rustc_lint/src/builtin.rs | 6 ++- compiler/rustc_middle/src/ty/diagnostics.rs | 9 ++-- compiler/rustc_passes/src/check_attr.rs | 6 ++- compiler/rustc_passes/src/stability.rs | 3 +- .../rustc_resolve/src/late/diagnostics.rs | 11 +++-- compiler/rustc_resolve/src/late/lifetimes.rs | 49 +++++++++++-------- .../src/traits/error_reporting/mod.rs | 7 +-- .../src/traits/error_reporting/suggestions.rs | 2 +- .../rustc_typeck/src/check/compare_method.rs | 24 +++++++-- compiler/rustc_typeck/src/check/wfcheck.rs | 5 +- compiler/rustc_typeck/src/coherence/orphan.rs | 2 +- compiler/rustc_typeck/src/collect.rs | 19 ++++--- .../clippy/clippy_lints/src/lifetimes.rs | 2 +- 16 files changed, 97 insertions(+), 67 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 7575e005a1dd1..640a8d89fe360 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -874,7 +874,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { hir_id: self.lower_node_id(node_id, span), name: hir_name, bounds: &[], - span, pure_wrt_drop: false, kind: hir::GenericParamKind::Lifetime { kind }, } @@ -1497,7 +1496,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { name: ParamName::Plain(ident), pure_wrt_drop: false, bounds: hir_bounds, - span, kind: hir::GenericParamKind::Type { default: None, synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), @@ -1785,7 +1783,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.output_lifetime_params.push(hir::GenericParam { hir_id, name, - span: lifetime.span, pure_wrt_drop: false, bounds: &[], kind: hir::GenericParamKind::Lifetime { kind }, @@ -2359,7 +2356,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { hir::GenericParam { hir_id, name, - span: param.ident.span, pure_wrt_drop: self.sess.contains_name(¶m.attrs, sym::may_dangle), bounds: self.arena.alloc_from_iter(bounds), kind, diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index e145fa7e0c4c1..c00f59e963ccc 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -16,7 +16,7 @@ use rustc_macros::HashStable_Generic; use rustc_span::source_map::{SourceMap, Spanned}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{def_id::LocalDefId, BytePos}; -use rustc_span::{MultiSpan, Span, DUMMY_SP}; +use rustc_span::{Span, DUMMY_SP}; use rustc_target::asm::InlineAsmRegOrRegClass; use rustc_target::spec::abi::Abi; @@ -471,7 +471,6 @@ pub struct GenericParam<'hir> { pub hir_id: HirId, pub name: ParamName, pub bounds: GenericBounds<'hir>, - pub span: Span, pub pure_wrt_drop: bool, pub kind: GenericParamKind<'hir>, } @@ -519,14 +518,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 diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index eeff48a63950e..7396a2b518307 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -163,7 +163,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) } @@ -174,7 +174,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_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 9affaf3892264..b1a2792594f1f 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -1487,7 +1487,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(); @@ -2142,8 +2143,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_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index f41bb7e6d6350..1291381881f54 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -129,7 +129,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| { @@ -157,7 +160,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; } @@ -187,7 +190,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_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 72ac776fb1d4e..e87fb40ea2bed 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -843,6 +843,7 @@ impl CheckAttrVisitor<'tcx> { match param.kind { hir::GenericParamKind::Const { .. } => {} _ => { + let param_span = self.tcx.hir().span(param.hir_id); self.tcx .sess .struct_span_err( @@ -850,7 +851,7 @@ impl CheckAttrVisitor<'tcx> { "#[rustc_legacy_const_generics] functions must \ only have const generics", ) - .span_label(param.span, "non-const generic parameter") + .span_label(param_span, "non-const generic parameter") .emit(); return false; } @@ -1219,7 +1220,8 @@ impl Visitor<'tcx> for CheckAttrVisitor<'tcx> { fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) { let target = Target::from_generic_param(generic_param); - self.check_attributes(generic_param.hir_id, &generic_param.span, target, None); + let span = self.tcx.hir().span(generic_param.hir_id); + self.check_attributes(generic_param.hir_id, &span, target, None); intravisit::walk_generic_param(self, generic_param) } diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 4bdd5a35df1fc..1d9fe77e8f9fb 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -517,9 +517,10 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { _ => AnnotationKind::Prohibited, }; + let span = self.tcx.hir().span(p.hir_id); self.annotate( p.hir_id, - p.span, + span, kind, InheritDeprecation::No, InheritConstStability::No, diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index e7b3d45976611..b4fe30c922aee 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -1670,7 +1670,8 @@ impl<'tcx> LifetimeContext<'_, 'tcx> { } ) }) { - (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)) @@ -1754,7 +1755,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 }); @@ -1868,7 +1872,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 afaa2a535689d..70cf28442321a 100644 --- a/compiler/rustc_resolve/src/late/lifetimes.rs +++ b/compiler/rustc_resolve/src/late/lifetimes.rs @@ -505,7 +505,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 { @@ -1073,8 +1075,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 { @@ -1090,7 +1093,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(); @@ -1415,8 +1418,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { param.kind, hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::InBand } ); + 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) @@ -1424,9 +1428,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 { @@ -1583,7 +1589,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, } { @@ -1640,7 +1647,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, } { @@ -2580,17 +2588,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(); } } @@ -2598,15 +2604,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(); } } @@ -2623,10 +2631,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(), @@ -2670,7 +2679,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { self.tcx, label.name, original_label(label.span), - shadower_lifetime(¶m), + shadower_lifetime(self.tcx, ¶m), ); return; } @@ -2697,7 +2706,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; } 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 a3faf4cb7d4c1..3b25704bb354d 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -1739,7 +1739,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() @@ -1769,9 +1770,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 65524df385f16..f768737de389a 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()) { diff --git a/compiler/rustc_typeck/src/check/compare_method.rs b/compiler/rustc_typeck/src/check/compare_method.rs index a30a81079335d..5700fae8f6b69 100644 --- a/compiler/rustc_typeck/src/check/compare_method.rs +++ b/compiler/rustc_typeck/src/check/compare_method.rs @@ -585,8 +585,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 @@ -595,7 +599,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(); @@ -615,11 +619,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/wfcheck.rs b/compiler/rustc_typeck/src/check/wfcheck.rs index 00c6550835b43..9f09100b59dc3 100644 --- a/compiler/rustc_typeck/src/check/wfcheck.rs +++ b/compiler/rustc_typeck/src/check/wfcheck.rs @@ -283,6 +283,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; @@ -328,7 +329,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 @@ -1260,7 +1261,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/coherence/orphan.rs b/compiler/rustc_typeck/src/coherence/orphan.rs index 05932427bcf7a..96721e92e6877 100644 --- a/compiler/rustc_typeck/src/coherence/orphan.rs +++ b/compiler/rustc_typeck/src/coherence/orphan.rs @@ -87,7 +87,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 68722c5a10afb..ca2f16bb31922 100644 --- a/compiler/rustc_typeck/src/collect.rs +++ b/compiler/rustc_typeck/src/collect.rs @@ -163,12 +163,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), )); } @@ -418,7 +420,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![ @@ -1258,7 +1261,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 \ @@ -2040,8 +2045,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/src/tools/clippy/clippy_lints/src/lifetimes.rs b/src/tools/clippy/clippy_lints/src/lifetimes.rs index 33ff01a30e881..cb0838221c765 100644 --- a/src/tools/clippy/clippy_lints/src/lifetimes.rs +++ b/src/tools/clippy/clippy_lints/src/lifetimes.rs @@ -475,7 +475,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(); From 4f527e96df6ddc26cc43a634d6a0d1d9dc2d094f Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 May 2020 11:58:13 +0200 Subject: [PATCH 16/41] Remove span from hir::Arm. --- compiler/rustc_ast_lowering/src/expr.rs | 4 ++-- compiler/rustc_hir/src/hir.rs | 1 - compiler/rustc_mir_build/src/thir/cx/expr.rs | 2 +- compiler/rustc_passes/src/check_attr.rs | 3 ++- src/tools/clippy/clippy_lints/src/loops/mod.rs | 2 +- src/tools/clippy/clippy_lints/src/matches.rs | 3 ++- src/tools/clippy/clippy_lints/src/methods/iter_next_slice.rs | 2 +- src/tools/clippy/clippy_lints/src/mut_mut.rs | 2 +- src/tools/clippy/clippy_lints/src/ranges.rs | 2 +- src/tools/clippy/clippy_lints/src/vec.rs | 2 +- src/tools/clippy/clippy_utils/src/higher.rs | 5 +++-- 11 files changed, 15 insertions(+), 13 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 83552f44850e6..91ee48dc8ab4b 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -627,7 +627,7 @@ impl<'hir> LoweringContext<'_, 'hir> { }); let hir_id = self.next_id(arm.span); self.lower_attrs(hir_id, &arm.attrs); - hir::Arm { hir_id, pat, guard, body: self.lower_expr(&arm.body), span: arm.span } + hir::Arm { hir_id, pat, guard, body: self.lower_expr(&arm.body) } } /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`. @@ -2169,6 +2169,6 @@ impl<'hir> LoweringContext<'_, 'hir> { } fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> { - hir::Arm { hir_id: self.next_id(expr.span), pat, guard: None, span: expr.span, body: expr } + hir::Arm { hir_id: self.next_id(expr.span), pat, guard: None, body: expr } } } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index c00f59e963ccc..19baf974e2f59 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1179,7 +1179,6 @@ pub struct Local<'hir> { pub struct Arm<'hir> { #[stable_hasher(ignore)] pub hir_id: HirId, - pub span: Span, /// If this pattern and the optional guard matches, then `body` is evaluated. pub pat: &'hir Pat<'hir>, /// Optional guard clause. diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index dfcb52c83c0d7..23edf8dc6a84a 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -839,7 +839,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { body: self.mirror_expr(arm.body), lint_level: LintLevel::Explicit(arm.hir_id), scope: region::Scope { id: arm.hir_id.local_id, data: region::ScopeData::Node }, - span: arm.span, + span: self.tcx.hir().span(arm.hir_id), } } diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index e87fb40ea2bed..e9cc91b2c118b 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1238,7 +1238,8 @@ impl Visitor<'tcx> for CheckAttrVisitor<'tcx> { } fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) { - self.check_attributes(arm.hir_id, &arm.span, Target::Arm, None); + let span = self.tcx.hir().span(arm.hir_id); + self.check_attributes(arm.hir_id, &span, Target::Arm, None); intravisit::walk_arm(self, arm); } diff --git a/src/tools/clippy/clippy_lints/src/loops/mod.rs b/src/tools/clippy/clippy_lints/src/loops/mod.rs index 2a372c6307eab..65f7aaee1f575 100644 --- a/src/tools/clippy/clippy_lints/src/loops/mod.rs +++ b/src/tools/clippy/clippy_lints/src/loops/mod.rs @@ -541,7 +541,7 @@ declare_lint_pass!(Loops => [ impl<'tcx> LateLintPass<'tcx> for Loops { #[allow(clippy::too_many_lines)] fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if let Some((pat, arg, body, span)) = higher::for_loop(expr) { + if let Some((pat, arg, body, span)) = higher::for_loop(cx, expr) { // we don't want to check expanded macros // this check is not at the top of the function // since higher::for_loop expressions are marked as expansions diff --git a/src/tools/clippy/clippy_lints/src/matches.rs b/src/tools/clippy/clippy_lints/src/matches.rs index cf10abf287a8b..8318ef97f067d 100644 --- a/src/tools/clippy/clippy_lints/src/matches.rs +++ b/src/tools/clippy/clippy_lints/src/matches.rs @@ -1296,7 +1296,8 @@ 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); + let arm_span = cx.tcx.hir().span(arms[0].hir_id); + if let Some(arm_snippet) = snippet_opt(cx, arm_span); 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("=>"); diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_next_slice.rs b/src/tools/clippy/clippy_lints/src/methods/iter_next_slice.rs index 3c03a949cfed0..c027ee8154962 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_next_slice.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_next_slice.rs @@ -17,7 +17,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, ite // since it is already covered by `&loops::ITER_NEXT_LOOP` let mut parent_expr_opt = get_parent_expr(cx, expr); while let Some(parent_expr) = parent_expr_opt { - if higher::for_loop(parent_expr).is_some() { + if higher::for_loop(cx, parent_expr).is_some() { return; } parent_expr_opt = get_parent_expr(cx, parent_expr); diff --git a/src/tools/clippy/clippy_lints/src/mut_mut.rs b/src/tools/clippy/clippy_lints/src/mut_mut.rs index d7239b328bbcd..23b4f1a1bb866 100644 --- a/src/tools/clippy/clippy_lints/src/mut_mut.rs +++ b/src/tools/clippy/clippy_lints/src/mut_mut.rs @@ -52,7 +52,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> { return; } - if let Some((_, arg, body, _)) = higher::for_loop(expr) { + if let Some((_, arg, body, _)) = higher::for_loop(self.cx, expr) { // A `for` loop lowers to: // ```rust // match ::std::iter::Iterator::next(&mut iter) { diff --git a/src/tools/clippy/clippy_lints/src/ranges.rs b/src/tools/clippy/clippy_lints/src/ranges.rs index 59503817c0fcc..687fd78d857ea 100644 --- a/src/tools/clippy/clippy_lints/src/ranges.rs +++ b/src/tools/clippy/clippy_lints/src/ranges.rs @@ -441,7 +441,7 @@ fn check_reversed_empty_range(cx: &LateContext<'_>, expr: &Expr<'_>) { fn is_for_loop_arg(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { let mut cur_expr = expr; while let Some(parent_expr) = get_parent_expr(cx, cur_expr) { - match higher::for_loop(parent_expr) { + match higher::for_loop(cx, parent_expr) { Some((_, args, _, _)) if args.hir_id == expr.hir_id => return true, _ => cur_expr = parent_expr, } diff --git a/src/tools/clippy/clippy_lints/src/vec.rs b/src/tools/clippy/clippy_lints/src/vec.rs index c132e4de4f67b..c5a930e4c6e0b 100644 --- a/src/tools/clippy/clippy_lints/src/vec.rs +++ b/src/tools/clippy/clippy_lints/src/vec.rs @@ -55,7 +55,7 @@ impl<'tcx> LateLintPass<'tcx> for UselessVec { // search for `for _ in vec![…]` if_chain! { - if let Some((_, arg, _, _)) = higher::for_loop(expr); + if let Some((_, arg, _, _)) = higher::for_loop(cx, expr); if let Some(vec_args) = higher::vec_macro(cx, arg); if is_copy(cx, vec_type(cx.typeck_results().expr_ty_adjusted(arg))); then { diff --git a/src/tools/clippy/clippy_utils/src/higher.rs b/src/tools/clippy/clippy_utils/src/higher.rs index be22df7109af7..3a8afbf6284fa 100644 --- a/src/tools/clippy/clippy_utils/src/higher.rs +++ b/src/tools/clippy/clippy_utils/src/higher.rs @@ -137,8 +137,9 @@ pub fn is_from_for_desugar(local: &hir::Local<'_>) -> bool { /// Recover the essential nodes of a desugared for loop as well as the entire span: /// `for pat in arg { body }` becomes `(pat, arg, body)`. Return `(pat, arg, body, span)`. pub fn for_loop<'tcx>( + cx: &LateContext<'_>, expr: &'tcx hir::Expr<'tcx>, -) -> Option<(&hir::Pat<'_>, &'tcx hir::Expr<'tcx>, &'tcx hir::Expr<'tcx>, Span)> { +) -> Option<(&'tcx hir::Pat<'tcx>, &'tcx hir::Expr<'tcx>, &'tcx hir::Expr<'tcx>, Span)> { if_chain! { if let hir::ExprKind::Match(ref iterexpr, ref arms, hir::MatchSource::ForLoopDesugar) = expr.kind; if let hir::ExprKind::Call(_, ref iterargs) = iterexpr.kind; @@ -149,7 +150,7 @@ pub fn for_loop<'tcx>( if let hir::StmtKind::Local(ref local) = let_stmt.kind; if let hir::StmtKind::Expr(ref expr) = body.kind; then { - return Some((&*local.pat, &iterargs[0], expr, arms[0].span)); + return Some((&*local.pat, &iterargs[0], expr, cx.tcx.hir().span(arms[0].hir_id))); } } None From 1fcff64d72353ed99ecf3c3e1b0ba08e8f53d88b Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 May 2020 12:07:57 +0200 Subject: [PATCH 17/41] Remove span from hir::FieldPat. --- compiler/rustc_ast_lowering/src/expr.rs | 1 - compiler/rustc_ast_lowering/src/lib.rs | 1 - compiler/rustc_ast_lowering/src/pat.rs | 1 - compiler/rustc_hir/src/hir.rs | 1 - compiler/rustc_lint/src/builtin.rs | 7 ++++--- compiler/rustc_privacy/src/lib.rs | 3 ++- compiler/rustc_typeck/src/check/pat.rs | 9 ++++++--- 7 files changed, 12 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 91ee48dc8ab4b..93f67d0c3ff7e 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -1122,7 +1122,6 @@ impl<'hir> LoweringContext<'_, 'hir> { ident: f.ident, pat, is_shorthand: f.is_shorthand, - span: f.span, } })); let qpath = self.lower_qpath( diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 640a8d89fe360..1c38135a3ff3c 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -2627,7 +2627,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ident: Ident::new(sym::integer(0), span), is_shorthand: false, pat, - span, }; arena_vec![self; field] } diff --git a/compiler/rustc_ast_lowering/src/pat.rs b/compiler/rustc_ast_lowering/src/pat.rs index d0f04f4f28228..f867ac0a989fc 100644 --- a/compiler/rustc_ast_lowering/src/pat.rs +++ b/compiler/rustc_ast_lowering/src/pat.rs @@ -61,7 +61,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ident: f.ident, pat: self.lower_pat(&f.pat), is_shorthand: f.is_shorthand, - span: f.span, })); break hir::PatKind::Struct(qpath, fs, etc); } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 19baf974e2f59..a9fe473413057 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -884,7 +884,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 diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index b1a2792594f1f..693500b5c1e78 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -248,7 +248,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) @@ -258,7 +259,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 { @@ -273,7 +274,7 @@ impl<'tcx> LateLintPass<'tcx> for NonShorthandFieldPatterns { ident.to_string() }; err.span_suggestion( - fieldpat.span, + fieldpat_span, "use shorthand field pattern", ident, Applicability::MachineApplicable, diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 9c47e8e64ccde..e6b10482cb66e 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -1101,7 +1101,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); } } diff --git a/compiler/rustc_typeck/src/check/pat.rs b/compiler/rustc_typeck/src/check/pat.rs index ac39bef590a5c..e3da550b34ed9 100644 --- a/compiler/rustc_typeck/src/check/pat.rs +++ b/compiler/rustc_typeck/src/check/pat.rs @@ -1179,7 +1179,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) => { @@ -1537,8 +1537,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .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, @@ -1606,7 +1607,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { [.., field] => { // Account for last field having a trailing comma or parse recovery at the tail of // the pattern to avoid invalid suggestion (#78511). - let tail = field.span.shrink_to_hi().with_hi(pat.span.hi()); + let field_span = self.tcx.hir().span(field.hir_id); + let pat_span = self.tcx.hir().span(pat.hir_id); + let tail = field_span.shrink_to_hi().with_hi(pat_span.hi()); match &pat.kind { PatKind::Struct(..) => (", ", " }", tail), _ => return err, From 3cf2fbaf27095875d6ad302fe05637446696326b Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 May 2020 12:16:25 +0200 Subject: [PATCH 18/41] Remove span from hir::Local. --- compiler/rustc_ast_lowering/src/lib.rs | 3 +-- compiler/rustc_hir/src/hir.rs | 1 - .../rustc_mir_build/src/thir/pattern/check_match.rs | 2 +- compiler/rustc_typeck/src/check/fn_ctxt/checks.rs | 3 ++- compiler/rustc_typeck/src/check/gather_locals.rs | 3 ++- compiler/rustc_typeck/src/check/writeback.rs | 5 +++-- src/tools/clippy/clippy_lints/src/default.rs | 3 ++- src/tools/clippy/clippy_lints/src/let_underscore.rs | 11 ++++++----- src/tools/clippy/clippy_lints/src/map_unit_fn.rs | 2 +- src/tools/clippy/clippy_lints/src/matches.rs | 9 +++++---- src/tools/clippy/clippy_lints/src/misc.rs | 3 ++- src/tools/clippy/clippy_lints/src/mut_key.rs | 3 ++- src/tools/clippy/clippy_lints/src/returns.rs | 9 +++++---- src/tools/clippy/clippy_lints/src/shadow.rs | 4 ++-- .../clippy/clippy_lints/src/vec_init_then_push.rs | 5 +++-- 15 files changed, 37 insertions(+), 29 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 1c38135a3ff3c..6fe2fdc0a2758 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1848,7 +1848,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ty, pat: self.lower_pat(&l.pat), init, - span: l.span, source: hir::LocalSource::Normal, }, ids, @@ -2568,7 +2567,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { debug_assert!(!a.is_empty()); self.attrs.insert(hir_id, a); } - let local = hir::Local { hir_id, init, pat, source, span, ty: None }; + let local = hir::Local { hir_id, init, pat, source, ty: None }; self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local))) } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index a9fe473413057..f9374bf4d79f9 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1166,7 +1166,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, /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop /// desugaring. Otherwise will be `Normal`. pub source: LocalSource, 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 fdecbb9478808..92a5d10c3bfd7 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), diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs index 9e07b056fed53..3c93dc8ca900b 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs @@ -518,7 +518,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. diff --git a/compiler/rustc_typeck/src/check/gather_locals.rs b/compiler/rustc_typeck/src/check/gather_locals.rs index fc420dc2c6495..e9e33382b9648 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 {}", diff --git a/compiler/rustc_typeck/src/check/writeback.rs b/compiler/rustc_typeck/src/check/writeback.rs index e189375a32e3a..06d0a1c48eb42 100644 --- a/compiler/rustc_typeck/src/check/writeback.rs +++ b/compiler/rustc_typeck/src/check/writeback.rs @@ -319,8 +319,9 @@ impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { 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/src/tools/clippy/clippy_lints/src/default.rs b/src/tools/clippy/clippy_lints/src/default.rs index b0cd8297c8bbe..820ed380909f6 100644 --- a/src/tools/clippy/clippy_lints/src/default.rs +++ b/src/tools/clippy/clippy_lints/src/default.rs @@ -210,12 +210,13 @@ 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_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/let_underscore.rs b/src/tools/clippy/clippy_lints/src/let_underscore.rs index 7e96dfcc7da0f..b4ab195fdcc08 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; } @@ -129,7 +130,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 \ @@ -139,7 +140,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 \ @@ -149,7 +150,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" @@ -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 a result of a `#[must_use]` function", None, "consider explicitly using function result" 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 c5548e3580cd6..ecb95e8b468cf 100644 --- a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs +++ b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs @@ -141,7 +141,7 @@ 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(cx.tcx.hir().span(inner_stmt.hir_id)), hir::StmtKind::Item(..) => None, diff --git a/src/tools/clippy/clippy_lints/src/matches.rs b/src/tools/clippy/clippy_lints/src/matches.rs index 8318ef97f067d..eeee44cfaccfa 100644 --- a/src/tools/clippy/clippy_lints/src/matches.rs +++ b/src/tools/clippy/clippy_lints/src/matches.rs @@ -608,9 +608,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(); @@ -627,7 +628,7 @@ 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", @@ -1340,7 +1341,7 @@ 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), diff --git a/src/tools/clippy/clippy_lints/src/misc.rs b/src/tools/clippy/clippy_lints/src/misc.rs index 69ebab6e3a783..7dfa670d415f3 100644 --- a/src/tools/clippy/clippy_lints/src/misc.rs +++ b/src/tools/clippy/clippy_lints/src/misc.rs @@ -311,7 +311,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, "..") diff --git a/src/tools/clippy/clippy_lints/src/mut_key.rs b/src/tools/clippy/clippy_lints/src/mut_key.rs index 908b7bb7ce00d..255e293676fe5 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/returns.rs b/src/tools/clippy/clippy_lints/src/returns.rs index 8c3c984f71062..fed2e494138fd 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, diff --git a/src/tools/clippy/clippy_lints/src/shadow.rs b/src/tools/clippy/clippy_lints/src/shadow.rs index 3f49d6ddcd8e7..79b1d9f0191ac 100644 --- a/src/tools/clippy/clippy_lints/src/shadow.rs +++ b/src/tools/clippy/clippy_lints/src/shadow.rs @@ -139,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) { @@ -149,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 { diff --git a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs index 30b96a7d0ad32..6417d1feb73f4 100644 --- a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs +++ b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs @@ -89,7 +89,8 @@ impl LateLintPass<'_> for VecInitThenPush { fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) { if_chain! { - if !in_external_macro(cx.sess(), local.span); + let local_span = cx.tcx.hir().span(local.hir_id); + if !in_external_macro(cx.sess(), local_span); if let Some(init) = local.init; if let PatKind::Binding(BindingAnnotation::Mutable, id, _, None) = local.pat.kind; if let Some(init_kind) = get_vec_init_kind(cx, init); @@ -99,7 +100,7 @@ impl LateLintPass<'_> for VecInitThenPush { init: init_kind, lhs_is_local: true, lhs_span: local.ty.map_or(local.pat.span, |t| local.pat.span.to(t.span)), - err_span: local.span, + err_span: local_span, found: 0, }); } From f51da1e4a42bbf50e1082af3739646f05734da35 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 6 Mar 2021 20:36:07 +0100 Subject: [PATCH 19/41] Remove span from hir::Pat. --- compiler/rustc_ast_lowering/src/item.rs | 2 +- compiler/rustc_ast_lowering/src/lib.rs | 9 +- compiler/rustc_ast_lowering/src/pat.rs | 1 - compiler/rustc_hir/src/hir.rs | 3 +- compiler/rustc_hir/src/pat_util.rs | 14 +- compiler/rustc_hir_pretty/src/lib.rs | 18 ++- .../infer/error_reporting/need_type_info.rs | 9 +- compiler/rustc_mir_build/src/build/mod.rs | 15 +- .../src/thir/pattern/check_match.rs | 44 +++--- .../rustc_mir_build/src/thir/pattern/mod.rs | 24 +-- compiler/rustc_passes/src/dead.rs | 2 +- compiler/rustc_passes/src/liveness.rs | 12 +- compiler/rustc_passes/src/naked_functions.rs | 4 +- compiler/rustc_passes/src/region.rs | 9 +- compiler/rustc_privacy/src/lib.rs | 3 +- .../src/traits/error_reporting/mod.rs | 9 +- compiler/rustc_typeck/src/check/_match.rs | 3 +- compiler/rustc_typeck/src/check/check.rs | 3 +- .../rustc_typeck/src/check/gather_locals.rs | 9 +- .../src/check/generator_interior.rs | 3 +- compiler/rustc_typeck/src/check/mod.rs | 3 +- compiler/rustc_typeck/src/check/pat.rs | 142 +++++++++++------- compiler/rustc_typeck/src/check/regionck.rs | 14 +- compiler/rustc_typeck/src/check/writeback.rs | 10 +- compiler/rustc_typeck/src/expr_use_visitor.rs | 8 +- .../rustc_typeck/src/mem_categorization.rs | 16 +- .../clippy_lints/src/collapsible_match.rs | 13 +- .../clippy/clippy_lints/src/functions.rs | 3 +- .../clippy_lints/src/if_let_some_result.rs | 2 +- .../src/loops/explicit_counter_loop.rs | 2 +- .../clippy_lints/src/loops/for_kv_map.rs | 8 +- .../src/loops/for_loops_over_fallibles.rs | 4 +- .../src/loops/needless_range_loop.rs | 4 +- .../clippy_lints/src/loops/while_let_loop.rs | 7 +- .../src/loops/while_let_on_iterator.rs | 3 +- .../clippy/clippy_lints/src/macro_use.rs | 5 +- .../clippy/clippy_lints/src/manual_map.rs | 6 +- .../clippy/clippy_lints/src/map_unit_fn.rs | 4 +- src/tools/clippy/clippy_lints/src/matches.rs | 56 ++++--- .../clippy/clippy_lints/src/methods/mod.rs | 2 +- src/tools/clippy/clippy_lints/src/misc.rs | 4 +- .../clippy_lints/src/needless_borrow.rs | 7 +- .../clippy_lints/src/needless_borrowed_ref.rs | 7 +- .../clippy_lints/src/pattern_type_mismatch.rs | 9 +- src/tools/clippy/clippy_lints/src/shadow.rs | 8 +- .../clippy/clippy_lints/src/types/mod.rs | 4 +- .../clippy_lints/src/vec_init_then_push.rs | 3 +- 47 files changed, 309 insertions(+), 241 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 8cd5b6db478ba..70a61436228e3 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1129,7 +1129,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. diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 6fe2fdc0a2758..035bde4bb697e 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -2656,7 +2656,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { 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, @@ -2668,19 +2667,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(span), - 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(span), kind, - span, default_binding_modes: false, }) } diff --git a/compiler/rustc_ast_lowering/src/pat.rs b/compiler/rustc_ast_lowering/src/pat.rs index f867ac0a989fc..440268ccde85e 100644 --- a/compiler/rustc_ast_lowering/src/pat.rs +++ b/compiler/rustc_ast_lowering/src/pat.rs @@ -275,7 +275,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.arena.alloc(hir::Pat { hir_id: self.lower_node_id(p.id, p.span), kind, - span: p.span, default_binding_modes: true, }) } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index f9374bf4d79f9..4affb9f22515d 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -798,7 +798,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, @@ -3056,7 +3055,7 @@ impl<'hir> Node<'hir> { mod size_asserts { rustc_data_structures::static_assert_size!(super::Block<'static>, 40); rustc_data_structures::static_assert_size!(super::Expr<'static>, 64); - rustc_data_structures::static_assert_size!(super::Pat<'static>, 88); + rustc_data_structures::static_assert_size!(super::Pat<'static>, 80); rustc_data_structures::static_assert_size!(super::QPath<'static>, 24); rustc_data_structures::static_assert_size!(super::Ty<'static>, 72); 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 8592c1fe24bd9..a175d484b6f80 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -341,18 +341,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(); } } @@ -360,7 +363,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]) { @@ -1237,7 +1240,7 @@ impl<'a> State<'a> { s.print_expr(&field.expr); s.end() }, - |f| f.span, + |_, f| f.span, ); match *wth { Some(ref expr) => { @@ -1887,7 +1890,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 @@ -1951,7 +1955,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_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index d533e267fd702..cbeefc8d7f88c 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 @@ -464,7 +464,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 @@ -637,12 +637,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() @@ -652,7 +653,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, _, exprs, _) = &e.kind { // Suggest impl candidates: diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index a6229a66587ad..5a63253e1723e 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -858,10 +858,15 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { argument_scope: region::Scope, expr: &Expr<'_, 'tcx>, ) -> BlockAnd<()> { + let tcx = self.tcx; + let tcx_hir = tcx.hir(); + let hir_typeck_results = self.typeck_results; + // 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)); + let source_info = 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. @@ -876,10 +881,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - let tcx = self.tcx; - let tcx_hir = tcx.hir(); - let hir_typeck_results = self.typeck_results; - // In analyze_closure() in upvar.rs we gathered a list of upvars used by a // indexed closure and we stored in a map called closure_captures in TypeckResults // with the closure's DefId. Here, we run through that vec of UpvarIds for @@ -954,7 +955,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(expr.span, |arg| arg.pat.span), + arg_opt.as_ref().map_or(expr.span, |arg| tcx_hir.span(arg.pat.hir_id)), argument_scope, local, DropKind::Value, 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 92a5d10c3bfd7..8ef1350bb2c1a 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -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, @@ -633,17 +637,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), @@ -655,7 +661,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") @@ -672,7 +678,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`. @@ -690,7 +697,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)); @@ -710,7 +717,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)); @@ -722,7 +729,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)); @@ -752,10 +759,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 9ac79a37ac690..ce9bee948fbbe 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -369,7 +369,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 @@ -512,6 +513,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, @@ -520,7 +522,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)); @@ -532,7 +534,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 } }; @@ -542,7 +544,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 }; } } @@ -551,7 +553,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) => { @@ -559,13 +561,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 } @@ -614,11 +616,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, _) => { @@ -631,13 +633,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/dead.rs b/compiler/rustc_passes/src/dead.rs index 4de5f11315742..3e6592ef0775d 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -157,7 +157,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 { diff --git a/compiler/rustc_passes/src/liveness.rs b/compiler/rustc_passes/src/liveness.rs index a96f332374430..b0c9140e6eed8 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, @@ -367,7 +367,7 @@ impl<'tcx> Visitor<'tcx> for IrMaps<'tcx> { } fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { - param.pat.each_binding(|_bm, hir_id, _x, ident| { + param.pat.each_binding(|_bm, hir_id, ident| { let var = match param.pat.kind { rustc_hir::PatKind::Struct(_, fields, _) => Local(LocalInfo { id: hir_id, @@ -554,7 +554,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); @@ -754,7 +755,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); }) @@ -1497,7 +1498,8 @@ impl<'tcx> Liveness<'_, 'tcx> { 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, ident.span); diff --git a/compiler/rustc_passes/src/naked_functions.rs b/compiler/rustc_passes/src/naked_functions.rs index a20e6b4cdbeac..bde260a17a540 100644 --- a/compiler/rustc_passes/src/naked_functions.rs +++ b/compiler/rustc_passes/src/naked_functions.rs @@ -91,7 +91,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 +104,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); }); } diff --git a/compiler/rustc_passes/src/region.rs b/compiler/rustc_passes/src/region.rs index b532021bed2e9..8a8ab556ebded 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_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index e6b10482cb66e..88628a304aacc 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -1322,7 +1322,8 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { // 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; } 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 3b25704bb354d..49a3f64988661 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -784,21 +784,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())) } }) diff --git a/compiler/rustc_typeck/src/check/_match.rs b/compiler/rustc_typeck/src/check/_match.rs index 4453f52209315..08185bd968af6 100644 --- a/compiler/rustc_typeck/src/check/_match.rs +++ b/compiler/rustc_typeck/src/check/_match.rs @@ -41,7 +41,8 @@ macro_rules! create_maybe_get_coercion_reason { } } if let hir::Node::Local(hir::Local { ty: Some(_), pat, .. }) = node { - return Some((pat.span, "expected because of this assignment".to_string())); + let pat_span = self.tcx.hir().span(pat.hir_id); + return Some((pat_span, "expected because of this assignment".to_string())); } None } diff --git a/compiler/rustc_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index ba6aa991eb524..1208d8268b733 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -182,7 +182,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); diff --git a/compiler/rustc_typeck/src/check/gather_locals.rs b/compiler/rustc_typeck/src/check/gather_locals.rs index e9e33382b9648..f00ddde4d6e40 100644 --- a/compiler/rustc_typeck/src/check/gather_locals.rs +++ b/compiler/rustc_typeck/src/check/gather_locals.rs @@ -100,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)); } } 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/mod.rs b/compiler/rustc_typeck/src/check/mod.rs index bb85336d7fb2d..983ced4eee286 100644 --- a/compiler/rustc_typeck/src/check/mod.rs +++ b/compiler/rustc_typeck/src/check/mod.rs @@ -700,7 +700,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 e3da550b34ed9..c7662be60001a 100644 --- a/compiler/rustc_typeck/src/check/pat.rs +++ b/compiler/rustc_typeck/src/check/pat.rs @@ -159,8 +159,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)); @@ -168,8 +169,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) } @@ -188,14 +189,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) } }; @@ -556,7 +557,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`, @@ -566,7 +568,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(_) => { @@ -574,12 +576,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 { @@ -626,7 +628,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match binding_parent { hir::Node::Param(hir::Param { hir_id, .. }) => { let span = tcx.hir().span(*hir_id); - 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) { err.span_suggestion( span, &format!("did you mean `{}`", snippet), @@ -637,9 +640,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, @@ -701,7 +706,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) { @@ -728,7 +734,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(..) @@ -743,12 +750,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 } @@ -876,10 +884,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_else(|_| String::new(), |s| format!(" `{}`", s.trim_end())); let msg = format!( "expected tuple struct or tuple variant, found {}{}", @@ -887,17 +896,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(); @@ -905,7 +914,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(); @@ -914,7 +923,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(); @@ -939,7 +948,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 @@ -956,14 +965,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(); } @@ -1036,7 +1046,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 parentheses", @@ -1047,8 +1060,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let after_fields_span = pat_span.with_hi(pat_span.hi() - BytePos(1)).shrink_to_hi(); let all_fields_span = match subpats { [] => after_fields_span, - [field] => field.span, - [first, .., last] => first.span.to(last.span), + [field] => self.tcx.hir().span(field.hir_id), + [first, .., last] => { + self.tcx.hir().span(first.hir_id).to(self.tcx.hir().span(last.hir_id)) + } }; // Check if all the fields in the pattern are wildcards. @@ -1061,8 +1076,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }); let tail_span = match first_tail_wildcard { None => after_fields_span, - Some(0) => subpats[0].span.to(after_fields_span), - Some(pos) => subpats[pos - 1].span.shrink_to_hi().to(after_fields_span), + Some(0) => self.tcx.hir().span(subpats[0].hir_id).to(after_fields_span), + Some(pos) => self + .tcx + .hir() + .span(subpats[pos - 1].hir_id) + .shrink_to_hi() + .to(after_fields_span), }; // FIXME: heuristic-based suggestion to check current types for where to add `_`. @@ -1159,9 +1179,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. @@ -1235,11 +1256,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, _)| { @@ -1305,15 +1326,16 @@ 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 ); err.span_suggestion_verbose( - qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()), + qpath.span().shrink_to_hi().to(pat_span.shrink_to_hi()), "use the tuple variant pattern syntax instead", format!("({})", self.get_suggested_tuple_struct_pattern(fields, variant)), Applicability::MaybeIncorrect, @@ -1327,13 +1349,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 @@ -1454,9 +1477,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 @@ -1473,7 +1497,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) }; err.span_suggestion_verbose( - qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()), + qpath.span().shrink_to_hi().to(pat_span.shrink_to_hi()), "use the tuple variant pattern syntax instead", format!("({})", sugg), appl, @@ -1492,7 +1516,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fields .iter() .map(|field| { - match self.tcx.sess.source_map().span_to_snippet(field.pat.span) { + match self + .tcx + .sess + .source_map() + .span_to_snippet(self.tcx.hir().span(field.pat.hir_id)) + { Ok(f) => { // Field names are numbers, but numbers // are not valid identifiers @@ -1531,10 +1560,11 @@ 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); @@ -1552,7 +1582,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", @@ -1588,19 +1618,20 @@ 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, }, @@ -1660,9 +1691,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); @@ -1686,7 +1718,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. @@ -1697,13 +1730,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 e28d8f3916844..f2e807a4aa507 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); @@ -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/writeback.rs b/compiler/rustc_typeck/src/check/writeback.rs index 06d0a1c48eb42..65f2c5af440cf 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) { @@ -294,11 +295,12 @@ impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { } 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); } @@ -311,9 +313,9 @@ 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); } diff --git a/compiler/rustc_typeck/src/expr_use_visitor.rs b/compiler/rustc_typeck/src/expr_use_visitor.rs index 52110af47929e..f1163427de2dd 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); } @@ -542,8 +543,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); @@ -554,7 +556,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 14af11097cf8b..b95d671fdc666 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)] @@ -672,10 +665,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)?; @@ -688,9 +682,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)?; @@ -704,7 +698,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/tools/clippy/clippy_lints/src/collapsible_match.rs b/src/tools/clippy/clippy_lints/src/collapsible_match.rs index 3c45525684be4..3e9d3eb100fb7 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, TypeckResults}; 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<'tcx>(arm: &Arm<'tcx>, wild_outer_arm: &Arm<'tcx>, 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 @@ -98,9 +98,10 @@ fn check_arm<'tcx>(arm: &Arm<'tcx>, wild_outer_arm: &Arm<'tcx>, 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"); }, ); @@ -136,7 +137,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 @@ -144,7 +145,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/functions.rs b/src/tools/clippy/clippy_lints/src/functions.rs index 3eefae05f30e2..e04a58647361b 100644 --- a/src/tools/clippy/clippy_lints/src/functions.rs +++ b/src/tools/clippy/clippy_lints/src/functions.rs @@ -577,8 +577,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/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/loops/explicit_counter_loop.rs b/src/tools/clippy/clippy_lints/src/loops/explicit_counter_loop.rs index 8d98b940c66a9..efafb52e9dc54 100644 --- a/src/tools/clippy/clippy_lints/src/loops/explicit_counter_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/explicit_counter_loop.rs @@ -46,7 +46,7 @@ pub(super) fn check<'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, diff --git a/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs b/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs index 6ee9b95a3b689..28acbcd4c9fb7 100644 --- a/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs +++ b/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs @@ -14,15 +14,17 @@ pub(super) fn check<'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(cx, key, body) => (pat[1].span, "value", ty, mutbl), - (_, value) if pat_is_wild(cx, value, body) => (pat[0].span, "key", ty, Mutability::Not), + (key, _) if pat_is_wild(cx, key, body) => (cx.tcx.hir().span(pat[1].hir_id), "value", ty, mutbl), + (_, value) if pat_is_wild(cx, value, body) => { + (cx.tcx.hir().span(pat[0].hir_id), "key", ty, Mutability::Not) + }, _ => return, }, _ => return, diff --git a/src/tools/clippy/clippy_lints/src/loops/for_loops_over_fallibles.rs b/src/tools/clippy/clippy_lints/src/loops/for_loops_over_fallibles.rs index db22d90a304bc..4c239c8bba2d1 100644 --- a/src/tools/clippy/clippy_lints/src/loops/for_loops_over_fallibles.rs +++ b/src/tools/clippy/clippy_lints/src/loops/for_loops_over_fallibles.rs @@ -20,7 +20,7 @@ pub(super) fn check(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, "_") ), ); @@ -37,7 +37,7 @@ pub(super) fn check(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, "_") ), ); diff --git a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs index 5f02e4b9d875d..83cd12538d79b 100644 --- a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs @@ -151,7 +151,7 @@ pub(super) fn check<'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), @@ -176,7 +176,7 @@ pub(super) fn check<'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)], ); }, ); diff --git a/src/tools/clippy/clippy_lints/src/loops/while_let_loop.rs b/src/tools/clippy/clippy_lints/src/loops/while_let_loop.rs index 65d8f2f1111a3..5a38a4216eca8 100644 --- a/src/tools/clippy/clippy_lints/src/loops/while_let_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/while_let_loop.rs @@ -37,7 +37,12 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, loop_block: &' "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, diff --git a/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs b/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs index e5a47694faa4e..bb9ebf22158d0 100644 --- a/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs +++ b/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs @@ -49,7 +49,8 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { 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, diff --git a/src/tools/clippy/clippy_lints/src/macro_use.rs b/src/tools/clippy/clippy_lints/src/macro_use.rs index 056ee195ce11c..229f3003e8786 100644 --- a/src/tools/clippy/clippy_lints/src/macro_use.rs +++ b/src/tools/clippy/clippy_lints/src/macro_use.rs @@ -144,8 +144,9 @@ impl<'tcx> LateLintPass<'tcx> for MacroUseImports { } } 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_map.rs b/src/tools/clippy/clippy_lints/src/manual_map.rs index ac1d51e1993b4..5c0b51ad47c31 100644 --- a/src/tools/clippy/clippy_lints/src/manual_map.rs +++ b/src/tools/clippy/clippy_lints/src/manual_map.rs @@ -168,8 +168,8 @@ impl LateLintPass<'_> for ManualMap { // TODO: handle explicit reference annotations. format!( "|{}| {}", - snippet_with_context(cx, some_pat.span, expr_ctxt, "..", &mut app), - snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app) + snippet_with_context(cx, cx.tcx.hir().span(some_pat.hir_id), expr_ctxt, "..", &mut app), + snippet_with_context(cx, cx.tcx.hir().span(some_expr.hir_id), expr_ctxt, "..", &mut app) ) } else { // Refutable bindings and mixed reference annotations can't be handled by `map`. @@ -279,7 +279,7 @@ fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ctxt: SyntaxCon .res .opt_def_id() .map_or(false, |id| match_def_path(cx, id, &paths::OPTION_SOME)) - && pat.span.ctxt() == ctxt => + && cx.tcx.hir().span(pat.hir_id).ctxt() == ctxt => { Some(OptionPat::Some { pattern, ref_count }) }, 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 ecb95e8b468cf..8a2e55fb36c6e 100644 --- a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs +++ b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs @@ -238,7 +238,7 @@ 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, "_") ); @@ -252,7 +252,7 @@ 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); diff --git a/src/tools/clippy/clippy_lints/src/matches.rs b/src/tools/clippy/clippy_lints/src/matches.rs index eeee44cfaccfa..cf8d157c4fb00 100644 --- a/src/tools/clippy/clippy_lints/src/matches.rs +++ b/src/tools/clippy/clippy_lints/src/matches.rs @@ -635,8 +635,8 @@ impl<'tcx> LateLintPass<'tcx> for Matches { 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, ); @@ -645,9 +645,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); @@ -659,7 +660,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", @@ -759,7 +760,7 @@ fn report_single_match_single_pattern( snippet(cx, ex.span, ".."), // PartialEq for different reference counts may not exist. "&".repeat(ref_count_diff), - snippet(cx, arms[0].pat.span, ".."), + snippet(cx, cx.tcx.hir().span(arms[0].pat.hir_id), ".."), expr_block(cx, &arms[0].body, None, "..", Some(expr.span)), els_str, ); @@ -768,7 +769,7 @@ fn report_single_match_single_pattern( let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`"; let sugg = 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, @@ -942,7 +943,7 @@ fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm // `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", @@ -969,9 +970,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); } } @@ -1100,7 +1101,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 } @@ -1174,7 +1178,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", @@ -1222,7 +1226,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 { @@ -1310,7 +1314,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() @@ -1347,7 +1351,12 @@ fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[A 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 ), ) @@ -1436,7 +1445,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), }); } @@ -1444,7 +1453,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)), }); } @@ -1696,7 +1705,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 ... = ... { ... } @@ -1939,8 +1948,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 _ @@ -1954,7 +1963,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), + ); } }, ); @@ -1974,6 +1986,6 @@ fn pat_contains_local(pat: &Pat<'_>, id: HirId) -> bool { /// Returns true if all the bindings in the `Pat` are in `ids` and vice versa fn bindings_eq(pat: &Pat<'_>, mut ids: FxHashSet) -> bool { let mut result = true; - pat.each_binding_or_first(&mut |_, id, _, _| result &= ids.remove(&id)); + pat.each_binding_or_first(&mut |_, id, _| result &= ids.remove(&id)); result && ids.is_empty() } diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index 7fd14c4f9b11c..86c951d024ce1 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -1888,7 +1888,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 7dfa670d415f3..bd0f550718c34 100644 --- a/src/tools/clippy/clippy_lints/src/misc.rs +++ b/src/tools/clippy/clippy_lints/src/misc.rs @@ -291,7 +291,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", ); @@ -331,7 +331,7 @@ 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( diff --git a/src/tools/clippy/clippy_lints/src/needless_borrow.rs b/src/tools/clippy/clippy_lints/src/needless_borrow.rs index 1aadcfd87b60f..5f8ed414db2ee 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 f449f397e7d61..20ddca6202e79 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrowed_ref.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrowed_ref.rs @@ -43,7 +43,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; } @@ -64,12 +65,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/pattern_type_mismatch.rs b/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs index 97e2e47c21124..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) { @@ -193,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/shadow.rs b/src/tools/clippy/clippy_lints/src/shadow.rs index 79b1d9f0191ac..cba8fe429854e 100644 --- a/src/tools/clippy/clippy_lints/src/shadow.rs +++ b/src/tools/clippy/clippy_lints/src/shadow.rs @@ -183,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; @@ -222,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 { @@ -343,13 +343,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/types/mod.rs b/src/tools/clippy/clippy_lints/src/types/mod.rs index 40a85953aaf60..4c8b133082e5a 100644 --- a/src/tools/clippy/clippy_lints/src/types/mod.rs +++ b/src/tools/clippy/clippy_lints/src/types/mod.rs @@ -416,7 +416,7 @@ impl<'tcx> LateLintPass<'tcx> for LetUnitValue { if let StmtKind::Local(ref local) = stmt.kind { if is_unit(cx.typeck_results().pat_ty(&local.pat)) { let stmt_span = cx.tcx.hir().span(stmt.hir_id); - if in_external_macro(cx.sess(), stmt_span) || local.pat.span.from_expansion() { + 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) { @@ -1458,7 +1458,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/vec_init_then_push.rs b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs index 6417d1feb73f4..8ebb17927cbd2 100644 --- a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs +++ b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs @@ -95,11 +95,12 @@ impl LateLintPass<'_> for VecInitThenPush { if let PatKind::Binding(BindingAnnotation::Mutable, id, _, None) = local.pat.kind; if let Some(init_kind) = get_vec_init_kind(cx, init); then { + let local_pat_span = cx.tcx.hir().span(local.pat.hir_id); self.searcher = Some(VecPushSearcher { local_id: id, init: init_kind, lhs_is_local: true, - lhs_span: local.ty.map_or(local.pat.span, |t| local.pat.span.to(t.span)), + lhs_span: local.ty.map_or(local_pat_span, |t| local_pat_span.to(t.span)), err_span: local_span, found: 0, }); From ec56b9fab0bf5fb41748a99b1d001b869c90e582 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 May 2020 14:38:22 +0200 Subject: [PATCH 20/41] Remove span from hir::Field. --- compiler/rustc_ast_lowering/src/expr.rs | 3 +-- compiler/rustc_hir/src/hir.rs | 1 - compiler/rustc_hir_pretty/src/lib.rs | 2 +- compiler/rustc_lint/src/types.rs | 4 +++- compiler/rustc_privacy/src/lib.rs | 5 +++-- compiler/rustc_typeck/src/check/expr.rs | 7 ++++--- 6 files changed, 12 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 93f67d0c3ff7e..3d3ab7540a84c 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -1666,7 +1666,6 @@ impl<'hir> LoweringContext<'_, 'hir> { hir_id: self.next_id(f.span), ident: f.ident, expr: self.lower_expr(&f.expr), - span: f.span, is_shorthand: f.is_shorthand, } } @@ -2164,7 +2163,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } fn field(&mut self, ident: Ident, expr: &'hir hir::Expr<'hir>, span: Span) -> hir::Field<'hir> { - hir::Field { hir_id: self.next_id(span), 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> { diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 4affb9f22515d..d36e43c204a04 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1196,7 +1196,6 @@ pub struct Field<'hir> { pub hir_id: HirId, pub ident: Ident, pub expr: &'hir Expr<'hir>, - pub span: Span, pub is_shorthand: bool, } diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index a175d484b6f80..09f1760fb8575 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -1240,7 +1240,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) => { diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 55662ee9c1522..8405ac3f725a3 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. diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 88628a304aacc..d3a818cc32cdb 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -1076,16 +1076,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); } } } diff --git a/compiler/rustc_typeck/src/check/expr.rs b/compiler/rustc_typeck/src/check/expr.rs index a504c987e7fbf..9fb8c0f89c280 100644 --- a/compiler/rustc_typeck/src/check/expr.rs +++ b/compiler/rustc_typeck/src/check/expr.rs @@ -1266,17 +1266,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) { From ec5cd7486ed33e2dec1a36465ed2e8795cce9ded Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 3 May 2020 10:56:22 +0200 Subject: [PATCH 21/41] Remove GenericArg::span. --- compiler/rustc_ast_lowering/src/path.rs | 7 ++--- compiler/rustc_hir/src/hir.rs | 16 +++------- .../borrow_check/diagnostics/region_name.rs | 2 +- compiler/rustc_typeck/src/astconv/generics.rs | 15 +++++----- compiler/rustc_typeck/src/astconv/mod.rs | 5 ++-- .../rustc_typeck/src/check/fn_ctxt/checks.rs | 3 +- .../wrong_number_of_generic_args.rs | 29 ++++++++++++------- 7 files changed, 39 insertions(+), 38 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index 4cec8cf2676ed..ffdbbaf0e5823 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -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| b.span)); if !generic_args.parenthesized && !has_lifetimes { generic_args.args = self .elided_path_lifetimes( diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index d36e43c204a04..75cfc5805319b 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -261,14 +261,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, @@ -355,17 +347,17 @@ impl GenericArgs<'_> { own_counts } - pub fn span(&self) -> Option { + pub fn span(&self, get_span: impl Fn(HirId) -> Span) -> Option { self.args .iter() .filter(|arg| !arg.is_synthetic()) - .map(|arg| arg.span()) + .map(|arg| get_span(arg.id())) .reduce(|span1, span2| span1.to(span2)) } /// Returns span encompassing arguments and their surrounding `<>` or `()` - pub fn span_ext(&self, sm: &SourceMap) -> Option { - let mut span = self.span()?; + pub fn span_ext(&self, sm: &SourceMap, get_span: impl Fn(HirId) -> Span) -> Option { + let mut span = self.span(get_span)?; let (o, c) = if self.parenthesized { ('(', ')') } else { ('<', '>') }; 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 03738f1b40a1c..a3426d0f69a81 100644 --- a/compiler/rustc_mir/src/borrow_check/diagnostics/region_name.rs +++ b/compiler/rustc_mir/src/borrow_check/diagnostics/region_name.rs @@ -637,7 +637,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { // HIR lowering sometimes doesn't catch this in erroneous // programs, so we need to use delay_span_bug here. See #82126. self.infcx.tcx.sess.delay_span_bug( - hir_arg.span(), + self.infcx.tcx.hir().span(hir_arg.id()), &format!("unmatched subst and hir arg: found {:?} vs {:?}", kind, hir_arg), ); } diff --git a/compiler/rustc_typeck/src/astconv/generics.rs b/compiler/rustc_typeck/src/astconv/generics.rs index 0ea0ccaceabd4..4f727a4b4b3be 100644 --- a/compiler/rustc_typeck/src/astconv/generics.rs +++ b/compiler/rustc_typeck/src/astconv/generics.rs @@ -29,9 +29,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(), @@ -46,8 +47,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let add_braces_suggestion = |arg: &GenericArg<'_>, err: &mut DiagnosticBuilder<'_>| { let suggestions = vec![ - (arg.span().shrink_to_lo(), String::from("{ ")), - (arg.span().shrink_to_hi(), String::from(" }")), + (tcx.hir().span(arg.id()).shrink_to_lo(), String::from("{ ")), + (tcx.hir().span(arg.id()).shrink_to_hi(), String::from(" }")), ]; err.multipart_suggestion( "if this generic argument was intended as a const parameter, \ @@ -102,7 +103,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, @@ -453,7 +454,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { invalid_args.extend( gen_args.args[args_offset + expected_max..args_offset + provided] .iter() - .map(|arg| arg.span()), + .map(|arg| tcx.hir().span(arg.id())), ); }; @@ -548,7 +549,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::>(); @@ -596,7 +597,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 947363fc3ed08..e194e27e0afeb 100644 --- a/compiler/rustc_typeck/src/astconv/mod.rs +++ b/compiler/rustc_typeck/src/astconv/mod.rs @@ -421,10 +421,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 diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs index 3c93dc8ca900b..468af6842bbef 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. diff --git a/compiler/rustc_typeck/src/structured_errors/wrong_number_of_generic_args.rs b/compiler/rustc_typeck/src/structured_errors/wrong_number_of_generic_args.rs index e35c155746642..2686f1da883ad 100644 --- a/compiler/rustc_typeck/src/structured_errors/wrong_number_of_generic_args.rs +++ b/compiler/rustc_typeck/src/structured_errors/wrong_number_of_generic_args.rs @@ -65,7 +65,7 @@ impl<'tcx> WrongNumberOfGenericArgs<'_, 'tcx> { let def_kind = self.tcx.def_kind(self.def_id).descr(self.def_id); let (quantifier, bound) = self.quantifier_and_bound(); - if self.gen_args.span().is_some() { + if self.gen_args.span(|id| self.tcx.hir().span(id)).is_some() { format!( "this {} takes {}{} {} argument{} but {}{} {} argument{} {} supplied", def_kind, @@ -122,7 +122,7 @@ impl<'tcx> WrongNumberOfGenericArgs<'_, 'tcx> { for (i, arg) in args { err.span_label( - arg.span(), + self.tcx.hir().span(arg.id()), if i + 1 == self.provided { format!( "supplied {} {} argument{}", @@ -139,7 +139,7 @@ impl<'tcx> WrongNumberOfGenericArgs<'_, 'tcx> { fn suggest(&self, err: &mut DiagnosticBuilder<'_>) { if self.provided == 0 { - if self.gen_args.span().is_some() { + if self.gen_args.span(|id| self.tcx.hir().span(id)).is_some() { self.suggest_adding_args(err); } else { self.suggest_creating_generics(err); @@ -206,11 +206,14 @@ impl<'tcx> WrongNumberOfGenericArgs<'_, 'tcx> { let missing_arg_count = self.expected_min - self.provided; let (span, sugg_prefix) = if self.args_offset + self.provided == 0 { - let span = self.gen_args.args[0].span().shrink_to_lo(); + let span = self.tcx.hir().span(self.gen_args.args[0].id()).shrink_to_lo(); (span, "") } else { - let span = - self.gen_args.args[self.args_offset + self.provided - 1].span().shrink_to_hi(); + let span = self + .tcx + .hir() + .span(self.gen_args.args[self.args_offset + self.provided - 1].id()) + .shrink_to_hi(); (span, ", ") }; @@ -249,7 +252,7 @@ impl<'tcx> WrongNumberOfGenericArgs<'_, 'tcx> { .path_segment .args .unwrap() - .span_ext(sm) + .span_ext(sm, |id| self.tcx.hir().span(id)) .unwrap() .with_lo(self.path_segment.ident.span.hi()); @@ -293,19 +296,23 @@ impl<'tcx> WrongNumberOfGenericArgs<'_, 'tcx> { let last_argument_ends_generics = to_idx + 1 == self.gen_args.args.len(); if !first_argument_starts_generics && last_argument_ends_generics { - (self.gen_args.args[from_idx - 1].span().hi(), true) + (self.tcx.hir().span(self.gen_args.args[from_idx - 1].id()).hi(), true) } else { - (self.gen_args.args[from_idx].span().lo(), false) + (self.tcx.hir().span(self.gen_args.args[from_idx].id()).lo(), false) } }; let to = { - let hi = self.gen_args.args[to_idx].span().hi(); + let hi = self.tcx.hir().span(self.gen_args.args[to_idx].id()).hi(); if comma_eaten { hi } else { - self.gen_args.args.get(to_idx + 1).map(|arg| arg.span().lo()).unwrap_or(hi) + self.gen_args + .args + .get(to_idx + 1) + .map(|arg| self.tcx.hir().span(arg.id()).lo()) + .unwrap_or(hi) } }; From 66e1a169ad0f2ed61c59723a38a6a6599c706db2 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Fri, 8 May 2020 10:45:02 +0200 Subject: [PATCH 22/41] Remove Span from hir::TypeBinding. --- compiler/rustc_ast_lowering/src/lib.rs | 1 - compiler/rustc_ast_lowering/src/path.rs | 4 ++-- compiler/rustc_hir/src/hir.rs | 1 - compiler/rustc_typeck/src/astconv/generics.rs | 2 +- compiler/rustc_typeck/src/astconv/mod.rs | 4 ++-- 5 files changed, 5 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 035bde4bb697e..3b00419e29042 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1262,7 +1262,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ident: constraint.ident, gen_args, kind, - span: constraint.span, } } diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index ffdbbaf0e5823..7104927d52fbe 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -268,7 +268,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { .args .first() .map(|a| self.spans[a.id()]) - .or_else(|| generic_args.bindings.first().map(|b| b.span)); + .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( @@ -428,6 +428,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let args = arena_vec![self;]; let bindings = arena_vec![self;]; let gen_args = self.arena.alloc(hir::GenericArgs { args, bindings, parenthesized: false }); - hir::TypeBinding { hir_id: self.next_id(span), gen_args, span, ident, kind } + hir::TypeBinding { hir_id: self.next_id(span), gen_args, ident, kind } } } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 75cfc5805319b..4ba529da98468 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2131,7 +2131,6 @@ pub struct TypeBinding<'hir> { pub ident: Ident, pub gen_args: &'hir GenericArgs<'hir>, pub kind: TypeBindingKind<'hir>, - pub span: Span, } // Represents the two kinds of type bindings. diff --git a/compiler/rustc_typeck/src/astconv/generics.rs b/compiler/rustc_typeck/src/astconv/generics.rs index 4f727a4b4b3be..3660e6e121543 100644 --- a/compiler/rustc_typeck/src/astconv/generics.rs +++ b/compiler/rustc_typeck/src/astconv/generics.rs @@ -432,7 +432,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let infer_lifetimes = gen_pos != GenericArgPosition::Type && arg_counts.lifetimes == 0; if gen_pos != GenericArgPosition::Type && !gen_args.bindings.is_empty() { - Self::prohibit_assoc_ty_binding(tcx, gen_args.bindings[0].span); + Self::prohibit_assoc_ty_binding(tcx, tcx.hir().span(gen_args.bindings[0].hir_id)); } let explicit_late_bound = diff --git a/compiler/rustc_typeck/src/astconv/mod.rs b/compiler/rustc_typeck/src/astconv/mod.rs index e194e27e0afeb..28ab952726f0c 100644 --- a/compiler/rustc_typeck/src/astconv/mod.rs +++ b/compiler/rustc_typeck/src/astconv/mod.rs @@ -572,7 +572,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { item_name: binding.ident, kind, gen_args: binding.gen_args, - span: binding.span, + span: tcx.hir().span(binding.hir_id), } }) .collect(); @@ -1897,7 +1897,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.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 From a29261d9330ac89623cd64a7b549e1c486952cb0 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Mon, 1 Jun 2020 20:48:40 +0200 Subject: [PATCH 23/41] Remove Span from hir::ConstArg. --- compiler/rustc_ast_lowering/src/lib.rs | 9 ++++----- compiler/rustc_hir/src/hir.rs | 1 - compiler/rustc_typeck/src/astconv/mod.rs | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 3b00419e29042..262bb39668a18 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1312,16 +1312,15 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { 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) }) + } } } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 4ba529da98468..ed441ddb41cee 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -250,7 +250,6 @@ impl<'hir> PathSegment<'hir> { #[derive(Encodable, Debug, HashStable_Generic)] pub struct ConstArg { pub value: AnonConst, - pub span: Span, } #[derive(Debug, HashStable_Generic)] diff --git a/compiler/rustc_typeck/src/astconv/mod.rs b/compiler/rustc_typeck/src/astconv/mod.rs index 28ab952726f0c..6345e1cb08722 100644 --- a/compiler/rustc_typeck/src/astconv/mod.rs +++ b/compiler/rustc_typeck/src/astconv/mod.rs @@ -1877,7 +1877,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!( From 56871a5b686605b47796af47f27fdba68ccac8db Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Mon, 1 Jun 2020 23:13:40 +0200 Subject: [PATCH 24/41] Remove Span from hir::TraitItemRef. --- compiler/rustc_ast_lowering/src/item.rs | 2 +- compiler/rustc_hir/src/hir.rs | 1 - compiler/rustc_hir/src/intravisit.rs | 2 +- compiler/rustc_middle/src/hir/map/collector.rs | 2 +- compiler/rustc_middle/src/ty/error.rs | 2 +- 5 files changed, 4 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 70a61436228e3..7c8650fc1373f 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -866,7 +866,7 @@ impl<'hir> LoweringContext<'_, 'hir> { }; let id = hir::TraitItemId { def_id: self.lower_node_id(i.id, i.span).expect_owner() }; 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`. diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index ed441ddb41cee..387c80c9763a2 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2823,7 +2823,6 @@ pub struct TraitItemRef { #[stable_hasher(project(name))] pub ident: Ident, pub kind: AssocItemKind, - pub span: Span, pub defaultness: Defaultness, } diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index 85bd96730cb9b..913f7f9935ba6 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -950,7 +950,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); diff --git a/compiler/rustc_middle/src/hir/map/collector.rs b/compiler/rustc_middle/src/hir/map/collector.rs index 7aa880d8874e1..6bdbf35d58f50 100644 --- a/compiler/rustc_middle/src/hir/map/collector.rs +++ b/compiler/rustc_middle/src/hir/map/collector.rs @@ -548,7 +548,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); } diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index f19cc99844926..0a8a724cccd8d 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -833,7 +833,7 @@ fn foo(&self) -> Self::T { String::new() } { if self.type_of(item.id.def_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", ); From 346176fb1a8f57d721f7005d6e9b9848adf3cad9 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Mon, 1 Jun 2020 23:23:21 +0200 Subject: [PATCH 25/41] Remove Span from hir::ImplItemRef. --- compiler/rustc_ast_lowering/src/item.rs | 1 - compiler/rustc_hir/src/hir.rs | 1 - compiler/rustc_hir/src/intravisit.rs | 2 +- compiler/rustc_middle/src/hir/map/collector.rs | 2 +- compiler/rustc_middle/src/ty/error.rs | 3 ++- compiler/rustc_trait_selection/src/traits/wf.rs | 2 +- src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs | 2 +- src/tools/clippy/clippy_lints/src/serde_api.rs | 4 ++-- 8 files changed, 8 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 7c8650fc1373f..4c6ed379950cf 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -948,7 +948,6 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::ImplItemRef { id: hir::ImplItemId { def_id: self.lower_node_id(i.id, i.span).expect_owner() }, ident: i.ident, - span: i.span, vis: self.lower_visibility(&i.vis, Some(i.id)), defaultness, kind: match &i.kind { diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 387c80c9763a2..bd04bb69edbf3 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2838,7 +2838,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, } diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index 913f7f9935ba6..bbbfa7acda8df 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -1000,7 +1000,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); diff --git a/compiler/rustc_middle/src/hir/map/collector.rs b/compiler/rustc_middle/src/hir/map/collector.rs index 6bdbf35d58f50..b6e10fb90499c 100644 --- a/compiler/rustc_middle/src/hir/map/collector.rs +++ b/compiler/rustc_middle/src/hir/map/collector.rs @@ -556,7 +556,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); } diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index 0a8a724cccd8d..62324522ab8c6 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -852,7 +852,8 @@ fn foo(&self) -> Self::T { String::new() } for item in &items[..] { if let hir::AssocItemKind::Type = item.kind { if self.type_of(item.id.def_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_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index e6ef9b137d899..dcbf91ef13075 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/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs b/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs index aca1ed5ca6563..1268bb83a8efe 100644 --- a/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs +++ b/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs @@ -46,7 +46,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/serde_api.rs b/src/tools/clippy/clippy_lints/src/serde_api.rs index 90cf1b6c86135..7fdc2ab8b8bdf 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())), _ => {}, } } From 64597506ca29acce59d64f467c547f98cc461f17 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Fri, 11 Dec 2020 23:31:45 +0100 Subject: [PATCH 26/41] Remove span from hir::ForeignItemRef. --- compiler/rustc_ast_lowering/src/item.rs | 1 - compiler/rustc_hir/src/hir.rs | 1 - compiler/rustc_hir/src/intravisit.rs | 2 +- compiler/rustc_middle/src/hir/map/collector.rs | 2 +- compiler/rustc_typeck/src/check/check.rs | 5 +++-- 5 files changed, 5 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 4c6ed379950cf..ad3a0c4fe514a 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -738,7 +738,6 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::ForeignItemRef { id: hir::ForeignItemId { def_id: self.lower_node_id(i.id, i.span).expect_owner() }, ident: i.ident, - span: i.span, vis: self.lower_visibility(&i.vis, Some(i.id)), } } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index bd04bb69edbf3..dacbc418b204f 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2876,7 +2876,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/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index bbbfa7acda8df..e0c496ffa10e8 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -992,7 +992,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); diff --git a/compiler/rustc_middle/src/hir/map/collector.rs b/compiler/rustc_middle/src/hir/map/collector.rs index b6e10fb90499c..480ec3d00b81b 100644 --- a/compiler/rustc_middle/src/hir/map/collector.rs +++ b/compiler/rustc_middle/src/hir/map/collector.rs @@ -564,7 +564,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_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index 1208d8268b733..3a1fd901eaacd 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -814,14 +814,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. From fcdfaf0ba164392628526c1d61ddd0f9ace7cff0 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 9 May 2020 12:23:57 +0200 Subject: [PATCH 27/41] Fix fulldeps tests. --- src/test/ui-fulldeps/auxiliary/lint-for-crate-rpass.rs | 3 ++- src/test/ui-fulldeps/auxiliary/lint-for-crate.rs | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) 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 8b1a3887f157f..ab5386e9de3a7 100644 --- a/src/test/ui-fulldeps/auxiliary/lint-for-crate-rpass.rs +++ b/src/test/ui-fulldeps/auxiliary/lint-for-crate-rpass.rs @@ -32,8 +32,9 @@ macro_rules! fake_lint_pass { $( if !cx.sess().contains_name(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 c9269d2b9baa8..22ebd3b3975fb 100644 --- a/src/test/ui-fulldeps/auxiliary/lint-for-crate.rs +++ b/src/test/ui-fulldeps/auxiliary/lint-for-crate.rs @@ -30,8 +30,9 @@ impl<'tcx> LateLintPass<'tcx> for Pass { let attrs = cx.tcx.hir().attrs(rustc_hir::CRATE_HIR_ID); if !cx.sess().contains_name(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() }); } From e6d9d4bd1322362fd1150004e671431edcb63271 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 13 Dec 2020 11:20:55 +0100 Subject: [PATCH 28/41] Fortify find_entry. --- compiler/rustc_middle/src/hir/map/mod.rs | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 9f90a2e2ef2fb..77c56c5517fe7 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -278,19 +278,18 @@ 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 instead 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)?; + let node = node.as_ref()?; + // FIXME(eddyb) use a single generic type instead 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, }) } } From 125796be908f7cd3448ba8dde6b14655012b4a11 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Thu, 10 Dec 2020 22:20:56 +0100 Subject: [PATCH 29/41] Remove Span from hir::CrateItem. --- compiler/rustc_ast_lowering/src/lib.rs | 2 +- compiler/rustc_hir/src/hir.rs | 1 - compiler/rustc_lint/src/builtin.rs | 3 ++- compiler/rustc_passes/src/entry.rs | 2 +- compiler/rustc_passes/src/stability.rs | 4 ++-- src/librustdoc/doctest.rs | 2 +- src/librustdoc/visit_ast.rs | 2 +- src/tools/clippy/clippy_lints/src/missing_doc.rs | 5 +++-- 8 files changed, 11 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 262bb39668a18..5810308615d4d 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -612,7 +612,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.spans.push_owner(Idx::new(self.resolver.definitions().def_index_count() - 1)); hir::Crate { - item: hir::CrateItem { module, span: c.span }, + item: hir::CrateItem { module }, 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, diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index dacbc418b204f..88920e63d16b4 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -612,7 +612,6 @@ pub struct ModuleItems { #[derive(Encodable, Debug, HashStable_Generic)] pub struct CrateItem<'hir> { pub module: Mod<'hir>, - pub span: Span, } /// The top-level data structure that stores the entire contents of diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 693500b5c1e78..3f5da45a37263 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -567,7 +567,8 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { } fn check_crate(&mut self, cx: &LateContext<'_>, krate: &hir::Crate<'_>) { - self.check_missing_docs_attrs(cx, hir::CRATE_HIR_ID, krate.item.span, "the", "crate"); + let span = cx.tcx.hir().span(hir::CRATE_HIR_ID); + self.check_missing_docs_attrs(cx, hir::CRATE_HIR_ID, span, "the", "crate"); for macro_def in krate.exported_macros { let attrs = cx.tcx.hir().attrs(macro_def.hir_id()); diff --git a/compiler/rustc_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index 57848208f945e..45fc449d661fe 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -171,7 +171,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/stability.rs b/compiler/rustc_passes/src/stability.rs index 1d9fe77e8f9fb..d68edda2052fa 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -693,7 +693,7 @@ fn new_index(tcx: TyCtxt<'tcx>) -> Index<'tcx> { annotator.annotate( hir::CRATE_HIR_ID, - krate.item.span, + tcx.hir().span(hir::CRATE_HIR_ID), AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -892,7 +892,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/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 505249c4f4de6..3217c7bc3574c 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -140,7 +140,7 @@ crate fn run(options: Options) -> Result<(), ErrorReported> { hir_collector.visit_testable( "".to_string(), CRATE_HIR_ID, - krate.item.span, + tcx.hir().span(CRATE_HIR_ID), |this| { intravisit::walk_crate(this, krate); }, diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index b6782fb75df35..675345a8824bb 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -72,7 +72,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { crate fn visit(mut self, krate: &'tcx hir::Crate<'_>) -> Module<'tcx> { let mut top_level_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/tools/clippy/clippy_lints/src/missing_doc.rs b/src/tools/clippy/clippy_lints/src/missing_doc.rs index 3a4c5b496da7f..49bdde15a92c8 100644 --- a/src/tools/clippy/clippy_lints/src/missing_doc.rs +++ b/src/tools/clippy/clippy_lints/src/missing_doc.rs @@ -126,9 +126,10 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { self.doc_hidden_stack.pop().expect("empty doc_hidden_stack"); } - fn check_crate(&mut self, cx: &LateContext<'tcx>, krate: &'tcx hir::Crate<'_>) { + fn check_crate(&mut self, cx: &LateContext<'tcx>, _: &'tcx hir::Crate<'_>) { let attrs = cx.tcx.hir().attrs(hir::CRATE_HIR_ID); - self.check_missing_docs_attrs(cx, attrs, krate.item.span, "the", "crate"); + let span = cx.tcx.hir().span(hir::CRATE_HIR_ID); + self.check_missing_docs_attrs(cx, attrs, span, "the", "crate"); } fn check_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx hir::Item<'_>) { From 7e26fd6624c6838fede00cc01f4eed99ff6bfd51 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 May 2020 19:04:59 +0200 Subject: [PATCH 30/41] Pass HirId in rustc_typeck::check. --- compiler/rustc_middle/src/ty/util.rs | 3 +- compiler/rustc_typeck/src/check/check.rs | 137 ++++++++++++----------- compiler/rustc_typeck/src/check/mod.rs | 15 ++- 3 files changed, 84 insertions(+), 71 deletions(-) diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 8edde8794ed27..bdcf66b3d0c27 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -836,7 +836,7 @@ impl<'tcx> ty::TyS<'tcx> { /// Check whether a type is representable. This means it cannot contain unboxed /// structural recursion. This check is needed for structs and enums. - pub fn is_representable(&'tcx self, tcx: TyCtxt<'tcx>, sp: Span) -> Representability { + pub fn is_representable(&'tcx self, tcx: TyCtxt<'tcx>, hir_id: hir::HirId) -> Representability { // Iterate until something non-representable is found fn fold_repr>(iter: It) -> Representability { iter.fold(Representability::Representable, |r1, r2| match (r1, r2) { @@ -995,6 +995,7 @@ impl<'tcx> ty::TyS<'tcx> { } debug!("is_type_representable: {:?}", self); + let sp = tcx.hir().span(hir_id); // To avoid a stack overflow when checking an enum variant or struct that // contains a different, structurally recursive type, maintain a stack diff --git a/compiler/rustc_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index 3a1fd901eaacd..a0c3c03d79bcb 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -9,7 +9,7 @@ use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE}; use rustc_hir::intravisit::Visitor; use rustc_hir::lang_items::LangItem; -use rustc_hir::{def::Res, ItemKind, Node, PathSegment}; +use rustc_hir::{def::Res, HirId, ItemKind, Node, PathSegment}; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt}; use rustc_middle::ty::fold::TypeFoldable; @@ -33,8 +33,9 @@ pub fn check_wf_new(tcx: TyCtxt<'_>) { tcx.hir().krate().par_visit_all_item_likes(&visit); } -pub(super) fn check_abi(tcx: TyCtxt<'_>, span: Span, abi: Abi) { +pub(super) fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, abi: Abi) { if !tcx.sess.target.is_abi_supported(abi) { + let span = tcx.hir().span(hir_id); struct_span_err!( tcx.sess, span, @@ -47,6 +48,7 @@ pub(super) fn check_abi(tcx: TyCtxt<'_>, span: Span, abi: Abi) { // This ABI is only allowed on function pointers if abi == Abi::CCmseNonSecureCall { + let span = tcx.hir().span(hir_id); struct_span_err!( tcx.sess, span, @@ -375,30 +377,30 @@ pub(super) fn check_fn<'a, 'tcx>( (fcx, gen_ty) } -fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) { +fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId) { let def = tcx.adt_def(def_id); def.destructor(tcx); // force the destructor to be evaluated - check_representable(tcx, span, def_id); + check_representable(tcx, def_id); if def.repr.simd() { - check_simd(tcx, span, def_id); + check_simd(tcx, def_id); } - check_transparent(tcx, span, def); - check_packed(tcx, span, def); + check_transparent(tcx, def_id, def); + check_packed(tcx, def_id, def); } -fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) { +fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) { let def = tcx.adt_def(def_id); def.destructor(tcx); // force the destructor to be evaluated - check_representable(tcx, span, def_id); - check_transparent(tcx, span, def); - check_union_fields(tcx, span, def_id); - check_packed(tcx, span, def); + check_representable(tcx, def_id); + check_transparent(tcx, def_id, def); + check_union_fields(tcx, def_id); + check_packed(tcx, def_id, def); } /// Check that the fields of the `union` do not need dropping. -fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool { +fn check_union_fields(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> bool { let item_type = tcx.type_of(item_def_id); if let ty::Adt(def, substs) = item_type.kind() { assert!(def.is_union()); @@ -421,13 +423,14 @@ fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> b } } } else { + let span = tcx.def_span(item_def_id); span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind()); } true } /// Check that a `static` is inhabited. -fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) { +fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) { // Make sure statics are inhabited. // Other parts of the compiler assume that there are no uninhabited places. In principle it // would be enough to check this for `extern` statics, as statics with an initializer will @@ -438,11 +441,13 @@ fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Spa Ok(l) => l, Err(_) => { // Generic statics are rejected, but we still reach this case. + let span = tcx.def_span(def_id); tcx.sess.delay_span_bug(span, "generic static must be rejected"); return; } }; if layout.abi.is_uninhabited() { + let span = tcx.def_span(def_id); tcx.struct_span_lint_hir( UNINHABITED_STATIC, tcx.hir().local_def_id_to_hir_id(def_id), @@ -458,33 +463,28 @@ fn check_static_inhabited<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Spa /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo` /// projections that would result in "inheriting lifetimes". -pub(super) fn check_opaque<'tcx>( +fn check_opaque<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, substs: SubstsRef<'tcx>, - span: Span, origin: &hir::OpaqueTyOrigin, ) { - check_opaque_for_inheriting_lifetimes(tcx, def_id, span); + check_opaque_for_inheriting_lifetimes(tcx, def_id); if tcx.type_of(def_id).references_error() { return; } - if check_opaque_for_cycles(tcx, def_id, substs, span, origin).is_err() { + if check_opaque_for_cycles(tcx, def_id, substs, origin).is_err() { return; } - check_opaque_meets_bounds(tcx, def_id, substs, span, origin); + check_opaque_meets_bounds(tcx, def_id, substs, origin); } /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result /// in "inheriting lifetimes". -#[instrument(level = "debug", skip(tcx, span))] -pub(super) fn check_opaque_for_inheriting_lifetimes( - tcx: TyCtxt<'tcx>, - def_id: LocalDefId, - span: Span, -) { +#[instrument(level = "debug", skip(tcx))] +fn check_opaque_for_inheriting_lifetimes(tcx: TyCtxt<'tcx>, def_id: LocalDefId) { let item = tcx.hir().expect_item(tcx.hir().local_def_id_to_hir_id(def_id)); - debug!(?item, ?span); + debug!(?item); struct FoundParentLifetime; struct FindParentLifetimeVisitor<'tcx>(&'tcx ty::Generics); @@ -591,6 +591,7 @@ pub(super) fn check_opaque_for_inheriting_lifetimes( _ => unreachable!(), }; + let span = tcx.def_span(def_id); let mut err = struct_span_err!( tcx.sess, span, @@ -614,21 +615,21 @@ pub(super) fn check_opaque_for_inheriting_lifetimes( } /// Checks that an opaque type does not contain cycles. -pub(super) fn check_opaque_for_cycles<'tcx>( +fn check_opaque_for_cycles<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, substs: SubstsRef<'tcx>, - span: Span, origin: &hir::OpaqueTyOrigin, ) -> Result<(), ErrorReported> { + let id = tcx.hir().local_def_id_to_hir_id(def_id); if let Err(partially_expanded_type) = tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs) { match origin { - hir::OpaqueTyOrigin::AsyncFn => async_opaque_type_cycle_error(tcx, span), + hir::OpaqueTyOrigin::AsyncFn => async_opaque_type_cycle_error(tcx, id), hir::OpaqueTyOrigin::Binding => { - binding_opaque_type_cycle_error(tcx, def_id, span, partially_expanded_type) + binding_opaque_type_cycle_error(tcx, id, partially_expanded_type) } - _ => opaque_type_cycle_error(tcx, def_id, span), + _ => opaque_type_cycle_error(tcx, id), } Err(ErrorReported) } else { @@ -653,7 +654,6 @@ fn check_opaque_meets_bounds<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, substs: SubstsRef<'tcx>, - span: Span, origin: &hir::OpaqueTyOrigin, ) { match origin { @@ -671,6 +671,7 @@ fn check_opaque_meets_bounds<'tcx>( let infcx = &inh.infcx; let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs); + let span = tcx.def_span(def_id); let misc_cause = traits::ObligationCause::misc(span, hir_id); let (_, opaque_type_map) = inh.register_infer_ok_obligations( @@ -717,26 +718,20 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { // Consts can play a role in type-checking, so they are included here. hir::ItemKind::Static(..) => { tcx.ensure().typeck(it.def_id); - maybe_check_static_with_link_section(tcx, it.def_id, it.span); - check_static_inhabited(tcx, it.def_id, it.span); + maybe_check_static_with_link_section(tcx, it.def_id); + check_static_inhabited(tcx, it.def_id); } hir::ItemKind::Const(..) => { tcx.ensure().typeck(it.def_id); } hir::ItemKind::Enum(ref enum_definition, _) => { - check_enum(tcx, it.span, &enum_definition.variants, it.def_id); + check_enum(tcx, &enum_definition.variants, it.def_id); } hir::ItemKind::Fn(..) => {} // entirely within check_item_body hir::ItemKind::Impl(ref impl_) => { debug!("ItemKind::Impl {} with id {:?}", it.ident, it.def_id); if let Some(impl_trait_ref) = tcx.impl_trait_ref(it.def_id) { - check_impl_items_against_trait( - tcx, - it.span, - it.def_id, - impl_trait_ref, - &impl_.items, - ); + check_impl_items_against_trait(tcx, it.def_id, impl_trait_ref, &impl_.items); let trait_def_id = impl_trait_ref.def_id; check_on_unimplemented(tcx, trait_def_id, it); } @@ -768,10 +763,10 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { } } hir::ItemKind::Struct(..) => { - check_struct(tcx, it.def_id, it.span); + check_struct(tcx, it.def_id); } hir::ItemKind::Union(..) => { - check_union(tcx, it.def_id, it.span); + check_union(tcx, it.def_id); } hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => { // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting @@ -780,7 +775,7 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { // See https://github.com/rust-lang/rust/issues/75100 if !tcx.sess.opts.actually_rustdoc { let substs = InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id()); - check_opaque(tcx, it.def_id, substs, it.span, &origin); + check_opaque(tcx, it.def_id, substs, &origin); } } hir::ItemKind::TyAlias(..) => { @@ -789,7 +784,7 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { check_type_params_are_used(tcx, &generics, pty_ty); } hir::ItemKind::ForeignMod { abi, items } => { - check_abi(tcx, it.span, abi); + check_abi(tcx, it.hir_id(), abi); if abi == Abi::RustIntrinsic { for item in items { @@ -842,7 +837,7 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span); } hir::ForeignItemKind::Static(..) => { - check_static_inhabited(tcx, def_id, item.span); + check_static_inhabited(tcx, item.def_id); } _ => {} } @@ -916,13 +911,14 @@ pub(super) fn check_specialization_validity<'tcx>( } } -pub(super) fn check_impl_items_against_trait<'tcx>( +fn check_impl_items_against_trait<'tcx>( tcx: TyCtxt<'tcx>, - full_impl_span: Span, impl_id: LocalDefId, impl_trait_ref: ty::TraitRef<'tcx>, impl_item_refs: &[hir::ImplItemRef<'_>], ) { + let full_impl_span = tcx.def_span(impl_id); + // If the trait reference itself is erroneous (so the compilation is going // to fail), skip checking the items here -- the `impl_item` table in `tcx` // isn't populated for such impls. @@ -1119,7 +1115,7 @@ fn report_mismatch_error<'tcx>( /// Checks whether a type can be represented in memory. In particular, it /// identifies types that contain themselves without indirection through a /// pointer, which would mean their size is unbounded. -pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool { +fn check_representable(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> bool { let rty = tcx.type_of(item_def_id); // Check that it is possible to represent this type. This call identifies @@ -1127,7 +1123,7 @@ pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalD // recursive type. It is only necessary to throw an error on those that // contain themselves. For case 2, there must be an inner type that will be // caught by case 1. - match rty.is_representable(tcx, sp) { + match rty.is_representable(tcx, tcx.hir().local_def_id_to_hir_id(item_def_id)) { Representability::SelfRecursive(spans) => { recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans); return false; @@ -1137,17 +1133,19 @@ pub(super) fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalD true } -pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) { +fn check_simd(tcx: TyCtxt<'_>, def_id: LocalDefId) { let t = tcx.type_of(def_id); if let ty::Adt(def, substs) = t.kind() { if def.is_struct() { let fields = &def.non_enum_variant().fields; if fields.is_empty() { + let sp = tcx.def_span(def_id); struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit(); return; } let e = fields[0].ty(tcx, substs); if !fields.iter().all(|f| f.ty(tcx, substs) == e) { + let sp = tcx.def_span(def_id); struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous") .span_label(sp, "SIMD elements must have the same type") .emit(); @@ -1160,6 +1158,7 @@ pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) { Some(fields.len() as u64) }; if let Some(len) = len { + let sp = tcx.def_span(def_id); if len == 0 { struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit(); return; @@ -1181,6 +1180,7 @@ pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) { _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ } ty::Array(ty, _c) if ty.is_machine() => { /* struct([f32; 4]) */ } _ => { + let sp = tcx.def_span(def_id); struct_span_err!( tcx.sess, sp, @@ -1196,7 +1196,7 @@ pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) { } } -pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) { +pub(super) fn check_packed(tcx: TyCtxt<'_>, def_id: LocalDefId, def: &ty::AdtDef) { let repr = def.repr; if repr.packed() { for attr in tcx.get_attrs(def.did).iter() { @@ -1204,6 +1204,7 @@ pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) { if let attr::ReprPacked(pack) = r { if let Some(repr_pack) = repr.pack { if pack as u64 != repr_pack.bytes() { + let sp = tcx.def_span(def_id); struct_span_err!( tcx.sess, sp, @@ -1217,6 +1218,7 @@ pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) { } } if repr.align.is_some() { + let sp = tcx.def_span(def_id); struct_span_err!( tcx.sess, sp, @@ -1226,6 +1228,7 @@ pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) { .emit(); } else { if let Some(def_spans) = check_packed_inner(tcx, def.did, &mut vec![]) { + let sp = tcx.def_span(def_id); let mut err = struct_span_err!( tcx.sess, sp, @@ -1296,10 +1299,15 @@ pub(super) fn check_packed_inner( None } -pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) { +pub(super) fn check_transparent<'tcx>( + tcx: TyCtxt<'tcx>, + def_id: LocalDefId, + adt: &'tcx ty::AdtDef, +) { if !adt.repr.transparent() { return; } + let sp = tcx.def_span(def_id); let sp = tcx.sess.source_map().guess_head_span(sp); if adt.is_union() && !tcx.features().transparent_unions { @@ -1354,18 +1362,14 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty } #[allow(trivial_numeric_casts)] -fn check_enum<'tcx>( - tcx: TyCtxt<'tcx>, - sp: Span, - vs: &'tcx [hir::Variant<'tcx>], - def_id: LocalDefId, -) { +fn check_enum<'tcx>(tcx: TyCtxt<'tcx>, vs: &'tcx [hir::Variant<'tcx>], def_id: LocalDefId) { let def = tcx.adt_def(def_id); def.destructor(tcx); // force the destructor to be evaluated if vs.is_empty() { let attributes = tcx.get_attrs(def_id.to_def_id()); if let Some(attr) = tcx.sess.find_by_name(&attributes, sym::repr) { + let sp = tcx.def_span(def_id); struct_span_err!( tcx.sess, attr.span, @@ -1380,6 +1384,7 @@ fn check_enum<'tcx>( let repr_type_ty = def.repr.discr_type().to_ty(tcx); if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 { if !tcx.features().repr128 { + let sp = tcx.def_span(def_id); feature_err( &tcx.sess.parse_sess, sym::repr128, @@ -1405,6 +1410,7 @@ fn check_enum<'tcx>( let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var)); if disr_non_unit || (disr_units && has_non_units) { + let sp = tcx.def_span(def_id); let mut err = struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified"); err.emit(); @@ -1440,8 +1446,8 @@ fn check_enum<'tcx>( disr_vals.push(discr); } - check_representable(tcx, sp, def_id); - check_transparent(tcx, sp, def); + check_representable(tcx, def_id); + check_transparent(tcx, def_id, def); } pub(super) fn check_type_params_are_used<'tcx>( @@ -1509,7 +1515,8 @@ pub(super) fn check_impl_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) { wfcheck::check_impl_item(tcx, def_id); } -fn async_opaque_type_cycle_error(tcx: TyCtxt<'tcx>, span: Span) { +fn async_opaque_type_cycle_error(tcx: TyCtxt<'tcx>, id: HirId) { + let span = tcx.hir().span(id); struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing") .span_label(span, "recursive `async fn`") .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`") @@ -1527,7 +1534,9 @@ fn async_opaque_type_cycle_error(tcx: TyCtxt<'tcx>, span: Span) { /// /// If all the return expressions evaluate to `!`, then we explain that the error will go away /// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder. -fn opaque_type_cycle_error(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) { +fn opaque_type_cycle_error(tcx: TyCtxt<'tcx>, id: HirId) { + let def_id = tcx.hir().local_def_id(id); + let span = tcx.hir().span(id); let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type"); let mut label = false; diff --git a/compiler/rustc_typeck/src/check/mod.rs b/compiler/rustc_typeck/src/check/mod.rs index 983ced4eee286..80cac7bee0841 100644 --- a/compiler/rustc_typeck/src/check/mod.rs +++ b/compiler/rustc_typeck/src/check/mod.rs @@ -108,7 +108,7 @@ use rustc_hir::def::Res; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; use rustc_hir::intravisit::Visitor; use rustc_hir::itemlikevisit::ItemLikeVisitor; -use rustc_hir::{HirIdMap, ImplicitSelfKind, Node}; +use rustc_hir::{HirId, HirIdMap, ImplicitSelfKind, Node}; use rustc_index::bit_set::BitSet; use rustc_index::vec::Idx; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; @@ -482,10 +482,10 @@ fn typeck_with_fallback<'tcx>( } let id = tcx.hir().local_def_id_to_hir_id(def_id); - let span = tcx.hir().span(id); // Figure out what primary body this item has. let (body_id, body_ty, fn_header, fn_decl) = primary_body_of(tcx, id).unwrap_or_else(|| { + let span = tcx.hir().span(id); span_bug!(span, "can't type-check body of {:?}", def_id); }); let body = tcx.hir().body(body_id); @@ -508,7 +508,7 @@ fn typeck_with_fallback<'tcx>( tcx.fn_sig(def_id) }; - check_abi(tcx, span, fn_sig.abi()); + check_abi(tcx, id, fn_sig.abi()); // Compute the fty from point of view of inside the fn. let fn_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), fn_sig); @@ -524,6 +524,7 @@ fn typeck_with_fallback<'tcx>( let fcx = check_fn(&inh, param_env, fn_sig, decl, id, body, None).0; fcx } else { + let span = tcx.hir().span(id); let fcx = FnCtxt::new(&inh, param_env, body.value.hir_id); let expected_type = body_ty .and_then(|ty| match ty.kind { @@ -681,10 +682,11 @@ fn get_owner_return_paths( /// Emit an error for recursive opaque types in a `let` binding. fn binding_opaque_type_cycle_error( tcx: TyCtxt<'tcx>, - def_id: LocalDefId, - span: Span, + id: HirId, partially_expanded_type: Ty<'tcx>, ) { + let def_id = tcx.hir().local_def_id(id); + let span = tcx.hir().span(id); let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type"); err.span_label(span, "cannot resolve opaque type"); // Find the owner that declared this `impl Trait` type. @@ -747,7 +749,8 @@ fn fn_maybe_err(tcx: TyCtxt<'_>, sp: Span, abi: Abi) { } } -fn maybe_check_static_with_link_section(tcx: TyCtxt<'_>, id: LocalDefId, span: Span) { +fn maybe_check_static_with_link_section(tcx: TyCtxt<'_>, id: LocalDefId) { + let span = tcx.def_span(id); // Only restricted on wasm32 target for now if !tcx.sess.opts.target_triple.triple().starts_with("wasm32") { return; From bdb83e281b789dd0607c58c2ec776f7f22b8af5e Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 May 2020 19:28:12 +0200 Subject: [PATCH 31/41] Pass HirId in rustc_lint. --- compiler/rustc_lint/src/builtin.rs | 47 ++++++++++++------------------ 1 file changed, 18 insertions(+), 29 deletions(-) diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 3f5da45a37263..d4fdbe8263b97 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -152,10 +152,11 @@ declare_lint! { declare_lint_pass!(BoxPointers => [BOX_POINTERS]); impl BoxPointers { - fn check_heap_type(&self, cx: &LateContext<'_>, span: Span, ty: Ty<'_>) { + fn check_heap_type(&self, cx: &LateContext<'_>, hir_id: HirId, ty: Ty<'_>) { for leaf in ty.walk() { if let GenericArgKind::Type(leaf_ty) = leaf.unpack() { if leaf_ty.is_box() { + let span = cx.tcx.hir().span(hir_id); cx.struct_span_lint(BOX_POINTERS, span, |lint| { lint.build(&format!("type uses owned (Box type) pointers: {}", ty)).emit() }); @@ -173,7 +174,7 @@ impl<'tcx> LateLintPass<'tcx> for BoxPointers { | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { - self.check_heap_type(cx, it.span, cx.tcx.type_of(it.def_id)) + self.check_heap_type(cx, it.hir_id(), cx.tcx.type_of(it.def_id)) } _ => (), } @@ -183,8 +184,7 @@ 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); - let span = cx.tcx.hir().span(struct_field.hir_id); - self.check_heap_type(cx, span, cx.tcx.type_of(def_id)); + self.check_heap_type(cx, struct_field.hir_id, cx.tcx.type_of(def_id)); } } _ => (), @@ -193,7 +193,7 @@ impl<'tcx> LateLintPass<'tcx> for BoxPointers { fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) { let ty = cx.typeck_results().node_type(e.hir_id); - self.check_heap_type(cx, e.span, ty); + self.check_heap_type(cx, e.hir_id, ty); } } @@ -511,7 +511,6 @@ impl MissingDoc { &self, cx: &LateContext<'_>, id: hir::HirId, - sp: Span, article: &'static str, desc: &'static str, ) { @@ -538,6 +537,7 @@ impl MissingDoc { let attrs = cx.tcx.hir().attrs(id); let has_doc = attrs.iter().any(|a| has_doc(cx.sess(), a)); if !has_doc { + let sp = cx.tcx.hir().span(id); cx.struct_span_lint( MISSING_DOCS, cx.tcx.sess.source_map().guess_head_span(sp), @@ -567,8 +567,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { } fn check_crate(&mut self, cx: &LateContext<'_>, krate: &hir::Crate<'_>) { - let span = cx.tcx.hir().span(hir::CRATE_HIR_ID); - self.check_missing_docs_attrs(cx, hir::CRATE_HIR_ID, span, "the", "crate"); + self.check_missing_docs_attrs(cx, hir::CRATE_HIR_ID, "the", "crate"); for macro_def in krate.exported_macros { let attrs = cx.tcx.hir().attrs(macro_def.hir_id()); @@ -627,7 +626,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { let (article, desc) = cx.tcx.article_and_description(it.def_id.to_def_id()); - self.check_missing_docs_attrs(cx, it.hir_id(), it.span, article, desc); + self.check_missing_docs_attrs(cx, it.hir_id(), article, desc); } fn check_trait_item(&mut self, cx: &LateContext<'_>, trait_item: &hir::TraitItem<'_>) { @@ -637,7 +636,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { let (article, desc) = cx.tcx.article_and_description(trait_item.def_id.to_def_id()); - self.check_missing_docs_attrs(cx, trait_item.hir_id(), trait_item.span, article, desc); + self.check_missing_docs_attrs(cx, trait_item.hir_id(), article, desc); } fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) { @@ -647,24 +646,22 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { } let (article, desc) = cx.tcx.article_and_description(impl_item.def_id.to_def_id()); - self.check_missing_docs_attrs(cx, impl_item.hir_id(), impl_item.span, article, desc); + self.check_missing_docs_attrs(cx, impl_item.hir_id(), article, desc); } fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'_>) { let (article, desc) = cx.tcx.article_and_description(foreign_item.def_id.to_def_id()); - self.check_missing_docs_attrs(cx, foreign_item.hir_id(), foreign_item.span, article, desc); + self.check_missing_docs_attrs(cx, foreign_item.hir_id(), article, desc); } fn check_struct_field(&mut self, cx: &LateContext<'_>, sf: &hir::StructField<'_>) { if !sf.is_positional() { - let span = cx.tcx.hir().span(sf.hir_id); - self.check_missing_docs_attrs(cx, sf.hir_id, span, "a", "struct field") + self.check_missing_docs_attrs(cx, sf.hir_id, "a", "struct field") } } fn check_variant(&mut self, cx: &LateContext<'_>, v: &hir::Variant<'_>) { - let span = cx.tcx.hir().span(v.id); - self.check_missing_docs_attrs(cx, v.id, span, "a", "variant"); + self.check_missing_docs_attrs(cx, v.id, "a", "variant"); } } @@ -1299,12 +1296,12 @@ impl UnreachablePub { what: &str, id: hir::HirId, vis: &hir::Visibility<'_>, - span: Span, exportable: bool, ) { let mut applicability = Applicability::MachineApplicable; match vis.node { hir::VisibilityKind::Public if !cx.access_levels.is_reachable(id) => { + let span = cx.tcx.hir().span(id); if span.from_expansion() { applicability = Applicability::MaybeIncorrect; } @@ -1337,27 +1334,19 @@ impl UnreachablePub { impl<'tcx> LateLintPass<'tcx> for UnreachablePub { fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { - self.perform_lint(cx, "item", item.hir_id(), &item.vis, item.span, true); + self.perform_lint(cx, "item", item.hir_id(), &item.vis, true); } fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'tcx>) { - self.perform_lint( - cx, - "item", - foreign_item.hir_id(), - &foreign_item.vis, - foreign_item.span, - true, - ); + self.perform_lint(cx, "item", foreign_item.hir_id(), &foreign_item.vis, true); } fn check_struct_field(&mut self, cx: &LateContext<'_>, field: &hir::StructField<'_>) { - let span = cx.tcx.hir().span(field.hir_id); - self.perform_lint(cx, "field", field.hir_id, &field.vis, span, false); + self.perform_lint(cx, "field", field.hir_id, &field.vis, false); } fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) { - self.perform_lint(cx, "item", impl_item.hir_id(), &impl_item.vis, impl_item.span, false); + self.perform_lint(cx, "item", impl_item.hir_id(), &impl_item.vis, false); } } From 05e913a0975869e662b20f5c8a943c4b7bc67bc8 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 May 2020 20:12:42 +0200 Subject: [PATCH 32/41] Pass HirId in rustc_passes::stability. --- compiler/rustc_passes/src/stability.rs | 64 ++++++++++---------------- 1 file changed, 24 insertions(+), 40 deletions(-) diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index d68edda2052fa..acf749cbdd85a 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -97,7 +97,6 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { fn annotate( &mut self, hir_id: HirId, - item_sp: Span, kind: AnnotationKind, inherit_deprecation: InheritDeprecation, inherit_const_stability: InheritConstStability, @@ -142,16 +141,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { } } - if self.tcx.features().staged_api { - if let Some(a) = attrs.iter().find(|a| self.tcx.sess.check_name(a, sym::deprecated)) { - self.tcx - .sess - .struct_span_err(a.span, "`#[deprecated]` cannot be used in staged API") - .span_label(a.span, "use `#[rustc_deprecated]` instead") - .span_label(item_sp, "") - .emit(); - } - } else { + if !self.tcx.features().staged_api { self.recurse_with_stability_attrs( depr.map(|(d, _)| DeprecationEntry::local(d, hir_id)), None, @@ -161,6 +151,16 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { return; } + let item_sp = self.tcx.hir().span_with_body(hir_id); + if let Some(a) = attrs.iter().find(|a| self.tcx.sess.check_name(a, sym::deprecated)) { + self.tcx + .sess + .struct_span_err(a.span, "`#[deprecated]` cannot be used in staged API") + .span_label(a.span, "use `#[rustc_deprecated]` instead") + .span_label(item_sp, "") + .emit(); + } + let (stab, const_stab) = attr::find_stability(&self.tcx.sess, attrs, item_sp); let const_stab = const_stab.map(|(const_stab, _)| { @@ -385,7 +385,6 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { if let Some(ctor_hir_id) = sd.ctor_hir_id() { self.annotate( ctor_hir_id, - i.span, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -399,7 +398,6 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { self.annotate( i.hir_id(), - i.span, kind, InheritDeprecation::Yes, const_stab_inherit, @@ -412,7 +410,6 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) { self.annotate( ti.hir_id(), - ti.span, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -428,7 +425,6 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { if self.in_trait_impl { AnnotationKind::Prohibited } else { AnnotationKind::Required }; self.annotate( ii.hir_id(), - ii.span, kind, InheritDeprecation::Yes, InheritConstStability::No, @@ -440,10 +436,8 @@ 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_span, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -452,7 +446,6 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { if let Some(ctor_hir_id) = var.data.ctor_hir_id() { v.annotate( ctor_hir_id, - var_span, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -467,10 +460,8 @@ 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, - span, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -484,7 +475,6 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) { self.annotate( i.hir_id(), - i.span, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -496,10 +486,8 @@ 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(), - span, AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -517,10 +505,8 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { _ => AnnotationKind::Prohibited, }; - let span = self.tcx.hir().span(p.hir_id); self.annotate( p.hir_id, - span, kind, InheritDeprecation::No, InheritConstStability::No, @@ -538,23 +524,25 @@ struct MissingStabilityAnnotations<'tcx> { } impl<'tcx> MissingStabilityAnnotations<'tcx> { - fn check_missing_stability(&self, hir_id: HirId, span: Span) { + fn check_missing_stability(&self, hir_id: HirId) { let stab = self.tcx.stability().local_stability(hir_id); let is_error = !self.tcx.sess.opts.test && stab.is_none() && self.access_levels.is_reachable(hir_id); if is_error { let def_id = self.tcx.hir().local_def_id(hir_id); let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id()); + let span = self.tcx.hir().span_with_body(hir_id); self.tcx.sess.span_err(span, &format!("{} has missing stability attribute", descr)); } } - fn check_missing_const_stability(&self, hir_id: HirId, span: Span) { + fn check_missing_const_stability(&self, hir_id: HirId) { let stab_map = self.tcx.stability(); let stab = stab_map.local_stability(hir_id); if stab.map_or(false, |stab| stab.level.is_stable()) { let const_stab = stab_map.local_const_stability(hir_id); if const_stab.is_none() { + let span = self.tcx.hir().span_with_body(hir_id); self.tcx.sess.span_err( span, "`#[stable]` const functions must also be either \ @@ -582,7 +570,7 @@ impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> { hir::ItemKind::Impl(hir::Impl { of_trait: None, .. }) | hir::ItemKind::ForeignMod { .. } ) { - self.check_missing_stability(i.hir_id(), i.span); + self.check_missing_stability(i.hir_id()); } // Ensure `const fn` that are `stable` have one of `rustc_const_unstable` or @@ -590,45 +578,42 @@ impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> { if self.tcx.features().staged_api && matches!(&i.kind, hir::ItemKind::Fn(sig, ..) if sig.header.is_const()) { - self.check_missing_const_stability(i.hir_id(), i.span); + self.check_missing_const_stability(i.hir_id()); } intravisit::walk_item(self, i) } fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) { - self.check_missing_stability(ti.hir_id(), ti.span); + self.check_missing_stability(ti.hir_id()); intravisit::walk_trait_item(self, ti); } fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) { let impl_def_id = self.tcx.hir().local_def_id(self.tcx.hir().get_parent_item(ii.hir_id())); if self.tcx.impl_trait_ref(impl_def_id).is_none() { - self.check_missing_stability(ii.hir_id(), ii.span); + self.check_missing_stability(ii.hir_id()); } intravisit::walk_impl_item(self, ii); } fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) { - let span = self.tcx.hir().span(var.id); - self.check_missing_stability(var.id, span); + self.check_missing_stability(var.id); intravisit::walk_variant(self, var, g, item_id); } fn visit_struct_field(&mut self, s: &'tcx StructField<'tcx>) { - let span = self.tcx.hir().span(s.hir_id); - self.check_missing_stability(s.hir_id, span); + self.check_missing_stability(s.hir_id); intravisit::walk_struct_field(self, s); } fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) { - self.check_missing_stability(i.hir_id(), i.span); + self.check_missing_stability(i.hir_id()); intravisit::walk_foreign_item(self, i); } fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef<'tcx>) { - let span = self.tcx.hir().span(md.hir_id()); - self.check_missing_stability(md.hir_id(), span); + self.check_missing_stability(md.hir_id()); } // Note that we don't need to `check_missing_stability` for default generic parameters, @@ -693,7 +678,6 @@ fn new_index(tcx: TyCtxt<'tcx>) -> Index<'tcx> { annotator.annotate( hir::CRATE_HIR_ID, - tcx.hir().span(hir::CRATE_HIR_ID), AnnotationKind::Required, InheritDeprecation::Yes, InheritConstStability::No, @@ -892,7 +876,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, tcx.hir().span(hir::CRATE_HIR_ID)); + missing.check_missing_stability(hir::CRATE_HIR_ID); intravisit::walk_crate(&mut missing, krate); krate.visit_all_item_likes(&mut missing.as_deep_visitor()); } From 203559319eb8ac0798c6ca6ec9f01e52d16e86ab Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 12 Dec 2020 00:27:18 +0100 Subject: [PATCH 33/41] Pass HirId in rustc_incremental::persist::dirty_clean. --- compiler/rustc_incremental/src/persist/dirty_clean.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index 0b544b8ab415e..e3b6401bdb73c 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -431,13 +431,14 @@ impl DirtyCleanVisitor<'tcx> { } } - fn check_item(&mut self, item_id: LocalDefId, item_span: Span) { + fn check_item(&mut self, item_id: LocalDefId) { for attr in self.tcx.get_attrs(item_id.to_def_id()).iter() { let assertion = match self.assertion_maybe(item_id, attr) { Some(a) => a, None => continue, }; self.checked_attrs.insert(attr.id); + let item_span = self.tcx.def_span(item_id); for dep_node in self.dep_nodes(&assertion.clean, item_id.to_def_id()) { self.assert_clean(item_span, dep_node); } @@ -450,19 +451,19 @@ impl DirtyCleanVisitor<'tcx> { impl ItemLikeVisitor<'tcx> for DirtyCleanVisitor<'tcx> { fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { - self.check_item(item.def_id, item.span); + self.check_item(item.def_id); } fn visit_trait_item(&mut self, item: &hir::TraitItem<'_>) { - self.check_item(item.def_id, item.span); + self.check_item(item.def_id); } fn visit_impl_item(&mut self, item: &hir::ImplItem<'_>) { - self.check_item(item.def_id, item.span); + self.check_item(item.def_id); } fn visit_foreign_item(&mut self, item: &hir::ForeignItem<'_>) { - self.check_item(item.def_id, item.span); + self.check_item(item.def_id); } } From cf99aea6882db00b8af2c66ca7177cef9b6d0d82 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 12 Dec 2020 00:42:00 +0100 Subject: [PATCH 34/41] Pass HirId in rustc_passes::check_attr. --- compiler/rustc_passes/src/check_attr.rs | 187 ++++++++---------- src/test/ui/asm/naked-invalid-attr.stderr | 11 +- ...sue-43106-gating-of-builtin-attrs-error.rs | 6 +- ...43106-gating-of-builtin-attrs-error.stderr | 41 +++- .../issue-43106-gating-of-builtin-attrs.rs | 6 +- ...issue-43106-gating-of-builtin-attrs.stderr | 39 +++- 6 files changed, 162 insertions(+), 128 deletions(-) diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index e9cc91b2c118b..2a49e30426950 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -22,7 +22,7 @@ use rustc_session::lint::builtin::{ }; use rustc_session::parse::feature_err; use rustc_span::symbol::{sym, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::Span; pub(crate) fn target_from_impl_item<'tcx>( tcx: TyCtxt<'tcx>, @@ -59,52 +59,46 @@ struct CheckAttrVisitor<'tcx> { impl CheckAttrVisitor<'tcx> { /// Checks any attribute. - fn check_attributes( - &self, - hir_id: HirId, - span: &Span, - target: Target, - item: Option>, - ) { + fn check_attributes(&self, hir_id: HirId, target: Target, item: Option>) { let mut is_valid = true; let attrs = self.tcx.hir().attrs(hir_id); for attr in attrs { is_valid &= if self.tcx.sess.check_name(attr, sym::inline) { - self.check_inline(hir_id, attr, span, target) + self.check_inline(hir_id, attr, target) } else if self.tcx.sess.check_name(attr, sym::non_exhaustive) { - self.check_non_exhaustive(hir_id, attr, span, target) + self.check_non_exhaustive(hir_id, attr, target) } else if self.tcx.sess.check_name(attr, sym::marker) { - self.check_marker(hir_id, attr, span, target) + self.check_marker(hir_id, attr, target) } else if self.tcx.sess.check_name(attr, sym::target_feature) { - self.check_target_feature(hir_id, attr, span, target) + self.check_target_feature(hir_id, attr, target) } else if self.tcx.sess.check_name(attr, sym::track_caller) { - self.check_track_caller(hir_id, &attr.span, attrs, span, target) + self.check_track_caller(hir_id, &attr.span, attrs, target) } else if self.tcx.sess.check_name(attr, sym::doc) { self.check_doc_attrs(attr, hir_id, target) } else if self.tcx.sess.check_name(attr, sym::no_link) { - self.check_no_link(hir_id, &attr, span, target) + self.check_no_link(hir_id, &attr, target) } else if self.tcx.sess.check_name(attr, sym::export_name) { - self.check_export_name(hir_id, &attr, span, target) + self.check_export_name(hir_id, &attr, target) } else if self.tcx.sess.check_name(attr, sym::rustc_args_required_const) { - self.check_rustc_args_required_const(&attr, span, target, item) + self.check_rustc_args_required_const(hir_id, &attr, target, item) } else if self.tcx.sess.check_name(attr, sym::allow_internal_unstable) { - self.check_allow_internal_unstable(hir_id, &attr, span, target, &attrs) + self.check_allow_internal_unstable(hir_id, &attr, target, &attrs) } else if self.tcx.sess.check_name(attr, sym::rustc_allow_const_fn_unstable) { - self.check_rustc_allow_const_fn_unstable(hir_id, &attr, span, target) + self.check_rustc_allow_const_fn_unstable(hir_id, &attr, target) } else if self.tcx.sess.check_name(attr, sym::naked) { - self.check_naked(hir_id, attr, span, target) + self.check_naked(hir_id, attr, target) } else if self.tcx.sess.check_name(attr, sym::rustc_legacy_const_generics) { - self.check_rustc_legacy_const_generics(&attr, span, target, item) + self.check_rustc_legacy_const_generics(hir_id, &attr, target, item) } else { // lint-only checks if self.tcx.sess.check_name(attr, sym::cold) { - self.check_cold(hir_id, attr, span, target); + self.check_cold(hir_id, attr, target); } else if self.tcx.sess.check_name(attr, sym::link_name) { - self.check_link_name(hir_id, attr, span, target); + self.check_link_name(hir_id, attr, target); } else if self.tcx.sess.check_name(attr, sym::link_section) { - self.check_link_section(hir_id, attr, span, target); + self.check_link_section(hir_id, attr, target); } else if self.tcx.sess.check_name(attr, sym::no_mangle) { - self.check_no_mangle(hir_id, attr, span, target); + self.check_no_mangle(hir_id, attr, target); } true }; @@ -118,7 +112,7 @@ impl CheckAttrVisitor<'tcx> { self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id)); } - self.check_repr(attrs, span, target, item, hir_id); + self.check_repr(attrs, target, item, hir_id); self.check_used(attrs, target); } @@ -158,7 +152,7 @@ impl CheckAttrVisitor<'tcx> { } /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid. - fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool { + fn check_inline(&self, hir_id: HirId, attr: &Attribute, target: Target) -> bool { match target { Target::Fn | Target::Closure @@ -195,13 +189,14 @@ impl CheckAttrVisitor<'tcx> { true } _ => { + let span = self.tcx.hir().span(hir_id); struct_span_err!( self.tcx.sess, attr.span, E0518, "attribute should be applied to function or closure", ) - .span_label(*span, "not a function or closure") + .span_label(span, "not a function or closure") .emit(); false } @@ -209,7 +204,7 @@ impl CheckAttrVisitor<'tcx> { } /// Checks if `#[naked]` is applied to a function definition. - fn check_naked(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool { + fn check_naked(&self, hir_id: HirId, attr: &Attribute, target: Target) -> bool { match target { Target::Fn | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true, @@ -222,13 +217,14 @@ impl CheckAttrVisitor<'tcx> { true } _ => { + let span = self.tcx.hir().span(hir_id); self.tcx .sess .struct_span_err( attr.span, "attribute should be applied to a function definition", ) - .span_label(*span, "not a function definition") + .span_label(span, "not a function definition") .emit(); false } @@ -241,7 +237,6 @@ impl CheckAttrVisitor<'tcx> { hir_id: HirId, attr_span: &Span, attrs: &'hir [Attribute], - span: &Span, target: Target, ) -> bool { match target { @@ -267,13 +262,14 @@ impl CheckAttrVisitor<'tcx> { true } _ => { + let span = self.tcx.hir().span(hir_id); struct_span_err!( self.tcx.sess, *attr_span, E0739, "attribute should be applied to function" ) - .span_label(*span, "not a function") + .span_label(span, "not a function") .emit(); false } @@ -281,13 +277,7 @@ impl CheckAttrVisitor<'tcx> { } /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid. - fn check_non_exhaustive( - &self, - hir_id: HirId, - attr: &Attribute, - span: &Span, - target: Target, - ) -> bool { + fn check_non_exhaustive(&self, hir_id: HirId, attr: &Attribute, target: Target) -> bool { match target { Target::Struct | Target::Enum | Target::Variant => true, // FIXME(#80564): We permit struct fields, match arms and macro defs to have an @@ -299,13 +289,14 @@ impl CheckAttrVisitor<'tcx> { true } _ => { + let span = self.tcx.hir().span(hir_id); struct_span_err!( self.tcx.sess, attr.span, E0701, "attribute can only be applied to a struct or enum" ) - .span_label(*span, "not a struct or enum") + .span_label(span, "not a struct or enum") .emit(); false } @@ -313,7 +304,7 @@ impl CheckAttrVisitor<'tcx> { } /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid. - fn check_marker(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool { + fn check_marker(&self, hir_id: HirId, attr: &Attribute, target: Target) -> bool { match target { Target::Trait => true, // FIXME(#80564): We permit struct fields, match arms and macro defs to have an @@ -325,10 +316,11 @@ impl CheckAttrVisitor<'tcx> { true } _ => { + let span = self.tcx.hir().span_with_body(hir_id); self.tcx .sess .struct_span_err(attr.span, "attribute can only be applied to a trait") - .span_label(*span, "not a trait") + .span_label(span, "not a trait") .emit(); false } @@ -336,13 +328,7 @@ impl CheckAttrVisitor<'tcx> { } /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid. - fn check_target_feature( - &self, - hir_id: HirId, - attr: &Attribute, - span: &Span, - target: Target, - ) -> bool { + fn check_target_feature(&self, hir_id: HirId, attr: &Attribute, target: Target) -> bool { match target { Target::Fn | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true, @@ -350,13 +336,14 @@ impl CheckAttrVisitor<'tcx> { // crates used this, so only emit a warning. Target::Statement => { self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { + let span = self.tcx.hir().span(hir_id); lint.build("attribute should be applied to a function") .warn( "this was previously accepted by the compiler but is \ being phased out; it will become a hard error in \ a future release!", ) - .span_label(*span, "not a function") + .span_label(span, "not a function") .emit(); }); true @@ -370,10 +357,11 @@ impl CheckAttrVisitor<'tcx> { true } _ => { + let span = self.tcx.hir().span(hir_id); self.tcx .sess .struct_span_err(attr.span, "attribute should be applied to a function") - .span_label(*span, "not a function") + .span_label(span, "not a function") .emit(); false } @@ -607,7 +595,7 @@ impl CheckAttrVisitor<'tcx> { } /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid. - fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) { + fn check_cold(&self, hir_id: HirId, attr: &Attribute, target: Target) { match target { Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {} // FIXME(#80564): We permit struct fields, match arms and macro defs to have an @@ -618,6 +606,7 @@ impl CheckAttrVisitor<'tcx> { self.inline_attr_str_error_with_macro_def(hir_id, attr, "cold"); } _ => { + let span = self.tcx.hir().span(hir_id); // FIXME: #[cold] was previously allowed on non-functions and some crates used // this, so only emit a warning. self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { @@ -627,7 +616,7 @@ impl CheckAttrVisitor<'tcx> { being phased out; it will become a hard error in \ a future release!", ) - .span_label(*span, "not a function") + .span_label(span, "not a function") .emit(); }); } @@ -635,7 +624,7 @@ impl CheckAttrVisitor<'tcx> { } /// Checks if `#[link_name]` is applied to an item other than a foreign function or static. - fn check_link_name(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) { + fn check_link_name(&self, hir_id: HirId, attr: &Attribute, target: Target) { match target { Target::ForeignFn | Target::ForeignStatic => {} // FIXME(#80564): We permit struct fields, match arms and macro defs to have an @@ -669,7 +658,8 @@ impl CheckAttrVisitor<'tcx> { } } - diag.span_label(*span, "not a foreign function or static"); + let span = self.tcx.hir().span_with_body(hir_id); + diag.span_label(span, "not a foreign function or static"); diag.emit(); }); } @@ -677,7 +667,7 @@ impl CheckAttrVisitor<'tcx> { } /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid. - fn check_no_link(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool { + fn check_no_link(&self, hir_id: HirId, attr: &Attribute, target: Target) -> bool { match target { Target::ExternCrate => true, // FIXME(#80564): We permit struct fields, match arms and macro defs to have an @@ -689,13 +679,14 @@ impl CheckAttrVisitor<'tcx> { true } _ => { + let span = self.tcx.hir().span_with_body(hir_id); self.tcx .sess .struct_span_err( attr.span, "attribute should be applied to an `extern crate` item", ) - .span_label(*span, "not an `extern crate` item") + .span_label(span, "not an `extern crate` item") .emit(); false } @@ -703,13 +694,7 @@ impl CheckAttrVisitor<'tcx> { } /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid. - fn check_export_name( - &self, - hir_id: HirId, - attr: &Attribute, - span: &Span, - target: Target, - ) -> bool { + fn check_export_name(&self, hir_id: HirId, attr: &Attribute, target: Target) -> bool { match target { Target::Static | Target::Fn | Target::Method(..) => true, // FIXME(#80564): We permit struct fields, match arms and macro defs to have an @@ -721,13 +706,14 @@ impl CheckAttrVisitor<'tcx> { true } _ => { + let span = self.tcx.hir().span(hir_id); self.tcx .sess .struct_span_err( attr.span, "attribute should be applied to a function or static", ) - .span_label(*span, "not a function or static") + .span_label(span, "not a function or static") .emit(); false } @@ -737,17 +723,18 @@ impl CheckAttrVisitor<'tcx> { /// Checks if `#[rustc_args_required_const]` is applied to a function and has a valid argument. fn check_rustc_args_required_const( &self, + hir_id: HirId, attr: &Attribute, - span: &Span, target: Target, item: Option>, ) -> bool { let is_function = matches!(target, Target::Fn | Target::Method(..) | Target::ForeignFn); if !is_function { + let span = self.tcx.hir().span(hir_id); self.tcx .sess .struct_span_err(attr.span, "attribute should be applied to a function") - .span_label(*span, "not a function") + .span_label(span, "not a function") .emit(); return false; } @@ -810,8 +797,8 @@ impl CheckAttrVisitor<'tcx> { /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument. fn check_rustc_legacy_const_generics( &self, + hir_id: HirId, attr: &Attribute, - span: &Span, target: Target, item: Option>, ) -> bool { @@ -820,7 +807,7 @@ impl CheckAttrVisitor<'tcx> { self.tcx .sess .struct_span_err(attr.span, "attribute should be applied to a function") - .span_label(*span, "not a function") + .span_label(self.tcx.hir().span(hir_id), "not a function") .emit(); return false; } @@ -908,7 +895,7 @@ impl CheckAttrVisitor<'tcx> { } /// Checks if `#[link_section]` is applied to a function or static. - fn check_link_section(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) { + fn check_link_section(&self, hir_id: HirId, attr: &Attribute, target: Target) { match target { Target::Static | Target::Fn | Target::Method(..) => {} // FIXME(#80564): We permit struct fields, match arms and macro defs to have an @@ -922,13 +909,14 @@ impl CheckAttrVisitor<'tcx> { // FIXME: #[link_section] was previously allowed on non-functions/statics and some // crates used this, so only emit a warning. self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { + let span = self.tcx.hir().span(hir_id); lint.build("attribute should be applied to a function or static") .warn( "this was previously accepted by the compiler but is \ being phased out; it will become a hard error in \ a future release!", ) - .span_label(*span, "not a function or static") + .span_label(span, "not a function or static") .emit(); }); } @@ -936,7 +924,7 @@ impl CheckAttrVisitor<'tcx> { } /// Checks if `#[no_mangle]` is applied to a function or static. - fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) { + fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, target: Target) { match target { Target::Static | Target::Fn | Target::Method(..) => {} // FIXME(#80564): We permit struct fields, match arms and macro defs to have an @@ -950,13 +938,14 @@ impl CheckAttrVisitor<'tcx> { // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some // crates used this, so only emit a warning. self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { + let span = self.tcx.hir().span(hir_id); lint.build("attribute should be applied to a function or static") .warn( "this was previously accepted by the compiler but is \ being phased out; it will become a hard error in \ a future release!", ) - .span_label(*span, "not a function or static") + .span_label(span, "not a function or static") .emit(); }); } @@ -967,7 +956,6 @@ impl CheckAttrVisitor<'tcx> { fn check_repr( &self, attrs: &'hir [Attribute], - span: &Span, target: Target, item: Option>, hir_id: HirId, @@ -1060,6 +1048,7 @@ impl CheckAttrVisitor<'tcx> { _ => continue, }; + let span = self.tcx.hir().span_with_body(hir_id); struct_span_err!( self.tcx.sess, hint.span(), @@ -1067,7 +1056,7 @@ impl CheckAttrVisitor<'tcx> { "{}", &format!("attribute should be applied to {} {}", article, allowed_targets) ) - .span_label(*span, &format!("not {} {}", article, allowed_targets)) + .span_label(span, &format!("not {} {}", article, allowed_targets)) .emit(); } @@ -1130,7 +1119,6 @@ impl CheckAttrVisitor<'tcx> { &self, hir_id: HirId, attr: &Attribute, - span: &Span, target: Target, attrs: &[Attribute], ) -> bool { @@ -1160,10 +1148,11 @@ impl CheckAttrVisitor<'tcx> { true } _ => { + let span = self.tcx.hir().span_with_body(hir_id); self.tcx .sess .struct_span_err(attr.span, "attribute should be applied to a macro") - .span_label(*span, "not a macro") + .span_label(span, "not a macro") .emit(); false } @@ -1176,7 +1165,6 @@ impl CheckAttrVisitor<'tcx> { &self, hir_id: HirId, attr: &Attribute, - span: &Span, target: Target, ) -> bool { match target { @@ -1194,10 +1182,11 @@ impl CheckAttrVisitor<'tcx> { true } _ => { + let span = self.tcx.hir().span_with_body(hir_id); self.tcx .sess .struct_span_err(attr.span, "attribute should be applied to `const fn`") - .span_label(*span, "not a `const fn`") + .span_label(span, "not a `const fn`") .emit(); false } @@ -1214,57 +1203,48 @@ impl Visitor<'tcx> for CheckAttrVisitor<'tcx> { fn visit_item(&mut self, item: &'tcx Item<'tcx>) { let target = Target::from_item(item); - self.check_attributes(item.hir_id(), &item.span, target, Some(ItemLike::Item(item))); + self.check_attributes(item.hir_id(), target, Some(ItemLike::Item(item))); intravisit::walk_item(self, item) } fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) { let target = Target::from_generic_param(generic_param); - let span = self.tcx.hir().span(generic_param.hir_id); - self.check_attributes(generic_param.hir_id, &span, target, None); + self.check_attributes(generic_param.hir_id, target, None); intravisit::walk_generic_param(self, generic_param) } fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) { let target = Target::from_trait_item(trait_item); - self.check_attributes(trait_item.hir_id(), &trait_item.span, target, None); + self.check_attributes(trait_item.hir_id(), target, None); intravisit::walk_trait_item(self, trait_item) } fn visit_struct_field(&mut self, struct_field: &'tcx hir::StructField<'tcx>) { - let span = self.tcx.hir().span(struct_field.hir_id); - self.check_attributes(struct_field.hir_id, &span, Target::Field, None); + self.check_attributes(struct_field.hir_id, Target::Field, None); intravisit::walk_struct_field(self, struct_field); } fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) { - let span = self.tcx.hir().span(arm.hir_id); - self.check_attributes(arm.hir_id, &span, Target::Arm, None); + self.check_attributes(arm.hir_id, Target::Arm, None); intravisit::walk_arm(self, arm); } fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) { let target = Target::from_foreign_item(f_item); - self.check_attributes( - f_item.hir_id(), - &f_item.span, - target, - Some(ItemLike::ForeignItem(f_item)), - ); + self.check_attributes(f_item.hir_id(), target, Some(ItemLike::ForeignItem(f_item))); intravisit::walk_foreign_item(self, f_item) } fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { let target = target_from_impl_item(self.tcx, impl_item); - self.check_attributes(impl_item.hir_id(), &impl_item.span, target, None); + self.check_attributes(impl_item.hir_id(), target, None); intravisit::walk_impl_item(self, impl_item) } 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 { - let stmt_span = self.tcx.hir().span(stmt.hir_id); - self.check_attributes(l.hir_id, &stmt_span, Target::Statement, None); + self.check_attributes(l.hir_id, Target::Statement, None); } intravisit::walk_stmt(self, stmt) } @@ -1275,7 +1255,7 @@ impl Visitor<'tcx> for CheckAttrVisitor<'tcx> { _ => Target::Expression, }; - self.check_attributes(expr.hir_id, &expr.span, target, None); + self.check_attributes(expr.hir_id, target, None); intravisit::walk_expr(self, expr) } @@ -1285,24 +1265,17 @@ impl Visitor<'tcx> for CheckAttrVisitor<'tcx> { generics: &'tcx hir::Generics<'tcx>, item_id: HirId, ) { - let span = self.tcx.hir().span(variant.id); - self.check_attributes(variant.id, &span, Target::Variant, None); + self.check_attributes(variant.id, Target::Variant, None); intravisit::walk_variant(self, variant, generics, item_id) } fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) { - let span = self.tcx.hir().span(macro_def.hir_id()); - self.check_attributes(macro_def.hir_id(), &span, Target::MacroDef, None); + self.check_attributes(macro_def.hir_id(), Target::MacroDef, None); intravisit::walk_macro_def(self, macro_def); } fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { - self.check_attributes( - param.hir_id, - &self.tcx.hir().span(param.hir_id), - Target::Param, - None, - ); + self.check_attributes(param.hir_id, Target::Param, None); intravisit::walk_param(self, param); } @@ -1370,7 +1343,7 @@ fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { tcx.hir().visit_exported_macros_in_krate(check_attr_visitor); check_invalid_macro_level_attr(tcx, tcx.hir().krate().non_exported_macro_attrs); if module_def_id.is_top_level_module() { - check_attr_visitor.check_attributes(CRATE_HIR_ID, &DUMMY_SP, Target::Mod, None); + check_attr_visitor.check_attributes(CRATE_HIR_ID, Target::Mod, None); check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs()); } } diff --git a/src/test/ui/asm/naked-invalid-attr.stderr b/src/test/ui/asm/naked-invalid-attr.stderr index 565c2986a66a7..490505ddb0e01 100644 --- a/src/test/ui/asm/naked-invalid-attr.stderr +++ b/src/test/ui/asm/naked-invalid-attr.stderr @@ -35,8 +35,15 @@ LL | fn f(); error: attribute should be applied to a function definition --> $DIR/naked-invalid-attr.rs:6:1 | -LL | #![naked] - | ^^^^^^^^^ +LL | / #![feature(asm)] +LL | | #![feature(naked_functions)] +LL | | #![naked] + | | ^^^^^^^^^ +LL | | +... | +LL | | #[naked] || {}; +LL | | } + | |_- not a function definition error: aborting due to 5 previous errors diff --git a/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs-error.rs b/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs-error.rs index 6404b2c3115cb..9e8c17882b534 100644 --- a/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs-error.rs +++ b/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs-error.rs @@ -1,6 +1,3 @@ -//~ NOTE: not an `extern crate` item -//~^ NOTE: not a function or static -//~^^ NOTE: not a function or closure // This is testing whether various builtin attributes signals an // error or warning when put in "weird" places. // @@ -12,6 +9,9 @@ #![macro_export] //~^ ERROR: `macro_export` attribute cannot be used at crate level +//~^^ NOTE: not an `extern crate` item +//~^^^ NOTE: not a function or static +//~^^^^ NOTE: not a function or closure #![main] //~^ ERROR: `main` attribute cannot be used at crate level #![start] diff --git a/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs-error.stderr b/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs-error.stderr index 3ca1bd2ea7e48..50f45be0ea5ef 100644 --- a/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs-error.stderr +++ b/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs-error.stderr @@ -116,23 +116,50 @@ LL | | } error: attribute should be applied to an `extern crate` item --> $DIR/issue-43106-gating-of-builtin-attrs-error.rs:26:1 | -LL | #![no_link] - | ^^^^^^^^^^^ +LL | / #![macro_export] +LL | | +LL | | +LL | | +... | +LL | | #![no_link] + | | ^^^^^^^^^^^ +... | +LL | | +LL | | fn main() {} + | |____________- not an `extern crate` item error: attribute should be applied to a function or static --> $DIR/issue-43106-gating-of-builtin-attrs-error.rs:28:1 | -LL | #![export_name = "2200"] - | ^^^^^^^^^^^^^^^^^^^^^^^^ +LL | / #![macro_export] +LL | | +LL | | +LL | | +... | +LL | | #![export_name = "2200"] + | | ^^^^^^^^^^^^^^^^^^^^^^^^ +... | +LL | | +LL | | fn main() {} + | |____________- not a function or static error[E0518]: attribute should be applied to function or closure --> $DIR/issue-43106-gating-of-builtin-attrs-error.rs:30:1 | -LL | #![inline] - | ^^^^^^^^^^ +LL | / #![macro_export] +LL | | +LL | | +LL | | +... | +LL | | #![inline] + | | ^^^^^^^^^^ +... | +LL | | +LL | | fn main() {} + | |____________- not a function or closure error: `macro_export` attribute cannot be used at crate level - --> $DIR/issue-43106-gating-of-builtin-attrs-error.rs:13:1 + --> $DIR/issue-43106-gating-of-builtin-attrs-error.rs:10:1 | LL | #![macro_export] | ^^^^^^^^^^^^^^^^ diff --git a/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs b/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs index 21f40524f63df..efbb8de1905a8 100644 --- a/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs +++ b/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs @@ -1,6 +1,3 @@ -//~ NOTE not a function -//~^ NOTE not a foreign function or static -//~^^ NOTE not a function or static // This test enumerates as many compiler-builtin ungated attributes as // possible (that is, all the mutually compatible ones), and checks // that we get "expected" (*) warnings for each in the various weird @@ -37,6 +34,9 @@ // ignore-tidy-linelength #![feature(test, plugin_registrar)] +//~^ NOTE not a function +//~^^ NOTE not a foreign function or static +//~^^^ NOTE not a function or static #![warn(unused_attributes, unknown_lints)] //~^ NOTE the lint level is defined here //~| NOTE the lint level is defined here diff --git a/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr b/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr index c864ccc868665..0acdd55d7fa57 100644 --- a/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr +++ b/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr @@ -312,24 +312,51 @@ LL | | } warning: attribute should be applied to a function --> $DIR/issue-43106-gating-of-builtin-attrs.rs:69:1 | -LL | #![cold] - | ^^^^^^^^ +LL | / #![feature(test, plugin_registrar)] +LL | | +LL | | +LL | | +... | +LL | | #![cold] + | | ^^^^^^^^ +... | +LL | | +LL | | fn main() {} + | |____________- not a function | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a foreign function or static --> $DIR/issue-43106-gating-of-builtin-attrs.rs:73:1 | -LL | #![link_name = "1900"] - | ^^^^^^^^^^^^^^^^^^^^^^ +LL | / #![feature(test, plugin_registrar)] +LL | | +LL | | +LL | | +... | +LL | | #![link_name = "1900"] + | | ^^^^^^^^^^^^^^^^^^^^^^ +... | +LL | | +LL | | fn main() {} + | |____________- not a foreign function or static | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a function or static --> $DIR/issue-43106-gating-of-builtin-attrs.rs:76:1 | -LL | #![link_section = "1800"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | / #![feature(test, plugin_registrar)] +LL | | +LL | | +LL | | +... | +LL | | #![link_section = "1800"] + | | ^^^^^^^^^^^^^^^^^^^^^^^^^ +... | +LL | | +LL | | fn main() {} + | |____________- not a function or static | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! From 85396f89be2d2a995ae471a4d82cad5f5022690f Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 12 Dec 2020 00:43:05 +0100 Subject: [PATCH 35/41] Pass HirId in rustc_passes::entry. --- compiler/rustc_passes/src/entry.rs | 46 +++++++++++++++++------------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/compiler/rustc_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index 45fc449d661fe..30fc9e04b5711 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -17,17 +17,17 @@ struct EntryContext<'a, 'tcx> { map: Map<'tcx>, /// The top-level function called `main`. - main_fn: Option<(HirId, Span)>, + main_fn: Option, /// The function that has attribute named `main`. - attr_main_fn: Option<(HirId, Span)>, + attr_main_fn: Option, /// The function that has the attribute 'start' on it. - start_fn: Option<(HirId, Span)>, + start_fn: Option, /// The functions that one might think are `main` but aren't, e.g. /// main functions not defined at the top level. For diagnostics. - non_main_fns: Vec<(HirId, Span)>, + non_main_fns: Vec, } impl<'a, 'tcx> ItemLikeVisitor<'tcx> for EntryContext<'a, 'tcx> { @@ -117,37 +117,42 @@ fn find_item(item: &Item<'_>, ctxt: &mut EntryContext<'_, '_>, at_root: bool) { } EntryPointType::MainNamed => { if ctxt.main_fn.is_none() { - ctxt.main_fn = Some((item.hir_id(), item.span)); + ctxt.main_fn = Some(item.hir_id()); } else { - struct_span_err!(ctxt.session, item.span, E0136, "multiple `main` functions") + let item_span = ctxt.map.span_with_body(item.hir_id()); + struct_span_err!(ctxt.session, item_span, E0136, "multiple `main` functions") .emit(); } } EntryPointType::OtherMain => { - ctxt.non_main_fns.push((item.hir_id(), item.span)); + ctxt.non_main_fns.push(item.hir_id()); } EntryPointType::MainAttr => { if ctxt.attr_main_fn.is_none() { - ctxt.attr_main_fn = Some((item.hir_id(), item.span)); + ctxt.attr_main_fn = Some(item.hir_id()); } else { + let item_span = ctxt.map.span_with_body(item.hir_id()); + let old_span = ctxt.map.span_with_body(ctxt.attr_main_fn.unwrap()); struct_span_err!( ctxt.session, - item.span, + item_span, E0137, "multiple functions with a `#[main]` attribute" ) - .span_label(item.span, "additional `#[main]` function") - .span_label(ctxt.attr_main_fn.unwrap().1, "first `#[main]` function") + .span_label(item_span, "additional `#[main]` function") + .span_label(old_span, "first `#[main]` function") .emit(); } } EntryPointType::Start => { if ctxt.start_fn.is_none() { - ctxt.start_fn = Some((item.hir_id(), item.span)); + ctxt.start_fn = Some(item.hir_id()); } else { - struct_span_err!(ctxt.session, item.span, E0138, "multiple `start` functions") - .span_label(ctxt.start_fn.unwrap().1, "previous `#[start]` function here") - .span_label(item.span, "multiple `start` functions") + let item_span = ctxt.map.span_with_body(item.hir_id()); + let old_span = ctxt.map.span_with_body(ctxt.start_fn.unwrap()); + struct_span_err!(ctxt.session, item_span, E0138, "multiple `start` functions") + .span_label(old_span, "previous `#[start]` function here") + .span_label(item_span, "multiple `start` functions") .emit(); } } @@ -158,11 +163,11 @@ fn configure_main( tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>, ) -> Option<(LocalDefId, EntryFnType)> { - if let Some((hir_id, _)) = visitor.start_fn { + if let Some(hir_id) = visitor.start_fn { Some((tcx.hir().local_def_id(hir_id), EntryFnType::Start)) - } else if let Some((hir_id, _)) = visitor.attr_main_fn { + } else if let Some(hir_id) = visitor.attr_main_fn { Some((tcx.hir().local_def_id(hir_id), EntryFnType::Main)) - } else if let Some((hir_id, _)) = visitor.main_fn { + } else if let Some(hir_id) = visitor.main_fn { Some((tcx.hir().local_def_id(hir_id), EntryFnType::Main)) } else { no_main_err(tcx, visitor); @@ -171,7 +176,7 @@ fn configure_main( } fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) { - let sp = tcx.hir().span(CRATE_HIR_ID); + let sp = tcx.hir().span_with_body(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. @@ -189,7 +194,8 @@ fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) { ); let filename = &tcx.sess.local_crate_source_file; let note = if !visitor.non_main_fns.is_empty() { - for &(_, span) in &visitor.non_main_fns { + for &hir_id in &visitor.non_main_fns { + let span = tcx.hir().span_with_body(hir_id); err.span_note(span, "here is a function named `main`"); } err.note("you have one or more functions named `main` not defined at the crate level"); From 042bf08aa16635f2fc30807fd0d8f834a224a0f3 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Tue, 22 Dec 2020 12:29:32 +0100 Subject: [PATCH 36/41] Remove span from hir::Item. --- compiler/rustc_ast_lowering/src/item.rs | 7 +-- compiler/rustc_ast_lowering/src/lib.rs | 1 - .../rustc_codegen_cranelift/src/driver/jit.rs | 4 +- compiler/rustc_codegen_ssa/src/mono_item.rs | 3 +- compiler/rustc_hir/src/hir.rs | 9 ++-- compiler/rustc_hir/src/intravisit.rs | 2 +- compiler/rustc_hir/src/stable_hash_impls.rs | 10 ++-- compiler/rustc_hir_pretty/src/lib.rs | 40 ++++++++++---- compiler/rustc_lint/src/builtin.rs | 18 ++++--- compiler/rustc_metadata/src/rmeta/encoder.rs | 16 ++++-- compiler/rustc_mir_build/src/build/mod.rs | 6 +-- compiler/rustc_passes/src/dead.rs | 15 +++--- compiler/rustc_passes/src/layout_test.rs | 13 ++--- compiler/rustc_passes/src/reachable.rs | 5 +- compiler/rustc_passes/src/stability.rs | 14 +++-- compiler/rustc_plugin_impl/src/build.rs | 10 ++-- compiler/rustc_privacy/src/lib.rs | 5 +- compiler/rustc_resolve/src/late/lifetimes.rs | 3 +- .../src/traits/error_reporting/mod.rs | 10 ++-- compiler/rustc_ty_utils/src/ty.rs | 8 ++- compiler/rustc_typeck/src/check/check.rs | 23 ++++---- .../rustc_typeck/src/check/method/suggest.rs | 11 ++-- compiler/rustc_typeck/src/check/mod.rs | 5 +- compiler/rustc_typeck/src/check/wfcheck.rs | 42 ++++++++------- compiler/rustc_typeck/src/check_unused.rs | 12 +++-- .../src/coherence/inherent_impls.rs | 54 ++++++++++--------- compiler/rustc_typeck/src/coherence/orphan.rs | 3 +- .../rustc_typeck/src/coherence/unsafety.rs | 9 ++-- compiler/rustc_typeck/src/collect.rs | 29 ++++++---- .../rustc_typeck/src/collect/item_bounds.rs | 10 ++-- compiler/rustc_typeck/src/collect/type_of.rs | 9 ++-- compiler/rustc_typeck/src/impl_wf_check.rs | 10 ++-- compiler/rustc_typeck/src/lib.rs | 6 ++- compiler/rustc_typeck/src/outlives/test.rs | 3 +- compiler/rustc_typeck/src/variance/test.rs | 3 +- src/librustdoc/clean/mod.rs | 8 +-- src/librustdoc/doctest.rs | 9 ++-- src/librustdoc/visit_ast.rs | 2 +- src/tools/clippy/clippy_lints/src/attrs.rs | 16 ++++-- .../clippy/clippy_lints/src/copy_iterator.rs | 2 +- src/tools/clippy/clippy_lints/src/derive.rs | 12 +++-- src/tools/clippy/clippy_lints/src/doc.rs | 15 +++--- .../clippy/clippy_lints/src/empty_enum.rs | 2 +- .../clippy_lints/src/exhaustive_items.rs | 7 +-- .../clippy_lints/src/fallible_impl_from.rs | 2 +- .../clippy/clippy_lints/src/from_over_into.rs | 2 +- .../clippy/clippy_lints/src/functions.rs | 43 +++++++++------ .../clippy/clippy_lints/src/inherent_impl.rs | 7 +-- .../clippy_lints/src/inherent_to_string.rs | 6 +-- .../clippy_lints/src/large_const_arrays.rs | 7 +-- .../clippy_lints/src/large_enum_variant.rs | 2 +- src/tools/clippy/clippy_lints/src/len_zero.rs | 4 +- .../clippy/clippy_lints/src/lifetimes.rs | 20 +++++-- .../clippy/clippy_lints/src/macro_use.rs | 5 +- .../clippy/clippy_lints/src/methods/mod.rs | 12 +++-- .../clippy/clippy_lints/src/missing_doc.rs | 18 +++++-- .../clippy/clippy_lints/src/missing_inline.rs | 14 +++-- .../clippy_lints/src/new_without_default.rs | 6 +-- .../clippy/clippy_lints/src/non_copy_const.rs | 8 +-- .../clippy_lints/src/pass_by_ref_or_value.rs | 3 +- .../clippy_lints/src/redundant_pub_crate.rs | 2 +- .../clippy/clippy_lints/src/types/mod.rs | 16 +++--- .../clippy/clippy_lints/src/unused_self.rs | 2 +- .../clippy_lints/src/unwrap_in_result.rs | 6 +-- src/tools/clippy/clippy_lints/src/use_self.rs | 2 +- .../clippy_lints/src/utils/internal_lints.rs | 12 +++-- .../clippy_lints/src/wildcard_imports.rs | 12 +++-- 67 files changed, 428 insertions(+), 284 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index ad3a0c4fe514a..4710006bfd1ce 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -240,7 +240,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let hir_id = self.lower_node_id(i.id, i.span); let attrs = self.lower_attrs(hir_id, &i.attrs); let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, &mut vis, &i.kind); - Some(hir::Item { def_id: hir_id.expect_owner(), ident, kind, vis, span: i.span }) + Some(hir::Item { def_id: hir_id.expect_owner(), ident, kind, vis }) } fn lower_item_kind( @@ -558,7 +558,6 @@ impl<'hir> LoweringContext<'_, 'hir> { ident, kind, vis, - span, }); }); } @@ -632,7 +631,6 @@ impl<'hir> LoweringContext<'_, 'hir> { ident, kind, vis, - span: use_tree.span, }); }); } @@ -849,7 +847,7 @@ impl<'hir> LoweringContext<'_, 'hir> { }; self.lower_attrs(hir_id, &i.attrs); - hir::TraitItem { def_id: trait_item_def_id, ident: i.ident, generics, kind, span: i.span } + hir::TraitItem { def_id: trait_item_def_id, ident: i.ident, generics, kind } } fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef { @@ -936,7 +934,6 @@ impl<'hir> LoweringContext<'_, 'hir> { vis: self.lower_visibility(&i.vis, None), defaultness, kind, - span: i.span, } } diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 5810308615d4d..43287658a931f 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1622,7 +1622,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ident: Ident::invalid(), kind: opaque_ty_item_kind, vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited), - span: opaque_ty_span, }; // Insert the item into the global item list. This usually happens diff --git a/compiler/rustc_codegen_cranelift/src/driver/jit.rs b/compiler/rustc_codegen_cranelift/src/driver/jit.rs index 245df03ffb84d..c0d3ba4196044 100644 --- a/compiler/rustc_codegen_cranelift/src/driver/jit.rs +++ b/compiler/rustc_codegen_cranelift/src/driver/jit.rs @@ -71,8 +71,8 @@ pub(super) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! { crate::constant::codegen_static(&mut cx.constants_cx, def_id); } MonoItem::GlobalAsm(item_id) => { - let item = cx.tcx.hir().item(item_id); - tcx.sess.span_fatal(item.span, "Global asm is not supported in JIT mode"); + let item_span = cx.tcx.hir().span(item_id.hir_id()); + tcx.sess.span_fatal(item_span, "Global asm is not supported in JIT mode"); } } } diff --git a/compiler/rustc_codegen_ssa/src/mono_item.rs b/compiler/rustc_codegen_ssa/src/mono_item.rs index 8e79193759eb4..38c745598a15f 100644 --- a/compiler/rustc_codegen_ssa/src/mono_item.rs +++ b/compiler/rustc_codegen_ssa/src/mono_item.rs @@ -35,7 +35,8 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> { if let hir::ItemKind::GlobalAsm(ref ga) = item.kind { cx.codegen_global_asm(ga); } else { - span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type") + let item_span = cx.tcx().def_span(item.def_id); + span_bug!(item_span, "Mismatch between hir::Item type and MonoItem type") } } MonoItem::Fn(instance) => { diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 88920e63d16b4..480ab5bc7e9c1 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2006,7 +2006,6 @@ pub struct TraitItem<'hir> { pub def_id: LocalDefId, pub generics: Generics<'hir>, pub kind: TraitItemKind<'hir>, - pub span: Span, } impl TraitItem<'_> { @@ -2068,7 +2067,6 @@ pub struct ImplItem<'hir> { pub defaultness: Defaultness, pub generics: Generics<'hir>, pub kind: ImplItemKind<'hir>, - pub span: Span, } impl ImplItem<'_> { @@ -2670,7 +2668,6 @@ pub struct Item<'hir> { pub def_id: LocalDefId, pub kind: ItemKind<'hir>, pub vis: Visibility<'hir>, - pub span: Span, } impl Item<'_> { @@ -3044,8 +3041,8 @@ mod size_asserts { rustc_data_structures::static_assert_size!(super::QPath<'static>, 24); rustc_data_structures::static_assert_size!(super::Ty<'static>, 72); - rustc_data_structures::static_assert_size!(super::Item<'static>, 184); - rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128); - rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 152); + rustc_data_structures::static_assert_size!(super::Item<'static>, 176); + rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 120); + rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 144); rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136); } diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index e0c496ffa10e8..f7cfb0f097d53 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -959,7 +959,7 @@ pub fn walk_trait_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, trait_item_ref: pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplItem<'v>) { // N.B., deliberately force a compilation error if/when new fields are added. - let ImplItem { def_id: _, ident, ref vis, ref defaultness, ref generics, ref kind, span: _ } = + let ImplItem { def_id: _, ident, ref vis, ref defaultness, ref generics, ref kind } = *impl_item; visitor.visit_ident(ident); diff --git a/compiler/rustc_hir/src/stable_hash_impls.rs b/compiler/rustc_hir/src/stable_hash_impls.rs index ea6af8c104e6b..ea9ab7fede823 100644 --- a/compiler/rustc_hir/src/stable_hash_impls.rs +++ b/compiler/rustc_hir/src/stable_hash_impls.rs @@ -139,21 +139,19 @@ impl HashStable for VisibilityKind<'_> impl HashStable for TraitItem<'_> { fn hash_stable(&self, hcx: &mut HirCtx, hasher: &mut StableHasher) { - let TraitItem { def_id: _, ident, ref generics, ref kind, span } = *self; + let TraitItem { def_id: _, ident, ref generics, ref kind } = *self; hcx.hash_hir_item_like(|hcx| { ident.name.hash_stable(hcx, hasher); generics.hash_stable(hcx, hasher); kind.hash_stable(hcx, hasher); - span.hash_stable(hcx, hasher); }); } } impl HashStable for ImplItem<'_> { fn hash_stable(&self, hcx: &mut HirCtx, hasher: &mut StableHasher) { - let ImplItem { def_id: _, ident, ref vis, defaultness, ref generics, ref kind, span } = - *self; + let ImplItem { def_id: _, ident, ref vis, defaultness, ref generics, ref kind } = *self; hcx.hash_hir_item_like(|hcx| { ident.name.hash_stable(hcx, hasher); @@ -161,7 +159,6 @@ impl HashStable for ImplItem<'_> { defaultness.hash_stable(hcx, hasher); generics.hash_stable(hcx, hasher); kind.hash_stable(hcx, hasher); - span.hash_stable(hcx, hasher); }); } } @@ -181,13 +178,12 @@ impl HashStable for ForeignItem<'_> { impl HashStable for Item<'_> { fn hash_stable(&self, hcx: &mut HirCtx, hasher: &mut StableHasher) { - let Item { ident, def_id: _, ref kind, ref vis, span } = *self; + let Item { ident, def_id: _, ref kind, ref vis } = *self; hcx.hash_hir_item_like(|hcx| { ident.name.hash_stable(hcx, hasher); kind.hash_stable(hcx, hasher); vis.hash_stable(hcx, hasher); - span.hash_stable(hcx, hasher); }); } } diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 09f1760fb8575..e0c3efe0caf3f 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -464,7 +464,7 @@ impl<'a> State<'a> { pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) { self.hardbreak_if_not_bol(); - self.maybe_print_comment(item.span.lo()); + self.maybe_print_comment(self.span(item.hir_id()).lo()); self.print_outer_attributes(self.attrs(item.hir_id())); match item.kind { hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => { @@ -572,7 +572,7 @@ impl<'a> State<'a> { /// Pretty-print an item pub fn print_item(&mut self, item: &hir::Item<'_>) { self.hardbreak_if_not_bol(); - self.maybe_print_comment(item.span.lo()); + self.maybe_print_comment(self.span(item.hir_id()).lo()); let attrs = self.attrs(item.hir_id()); self.print_outer_attributes(attrs); self.ann.pre(self, AnnNode::Item(item)); @@ -660,7 +660,7 @@ impl<'a> State<'a> { self.nbsp(); self.bopen(); self.print_mod(_mod, attrs); - self.bclose(item.span); + self.bclose(self.span(item.hir_id())); } hir::ItemKind::ForeignMod { abi, items } => { self.head("extern"); @@ -670,7 +670,7 @@ impl<'a> State<'a> { for item in items { self.ann.nested(self, Nested::ForeignItem(item.id)); } - self.bclose(item.span); + self.bclose(self.span(item.hir_id())); } hir::ItemKind::GlobalAsm(ref ga) => { self.head(visibility_qualified(&item.vis, "global asm")); @@ -699,15 +699,33 @@ impl<'a> State<'a> { }); } hir::ItemKind::Enum(ref enum_definition, ref params) => { - self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis); + self.print_enum_def( + enum_definition, + params, + item.ident.name, + self.span(item.hir_id()), + &item.vis, + ); } hir::ItemKind::Struct(ref struct_def, ref generics) => { self.head(visibility_qualified(&item.vis, "struct")); - self.print_struct(struct_def, generics, item.ident.name, item.span, true); + self.print_struct( + struct_def, + generics, + item.ident.name, + self.span(item.hir_id()), + true, + ); } hir::ItemKind::Union(ref struct_def, ref generics) => { self.head(visibility_qualified(&item.vis, "union")); - self.print_struct(struct_def, generics, item.ident.name, item.span, true); + self.print_struct( + struct_def, + generics, + item.ident.name, + self.span(item.hir_id()), + true, + ); } hir::ItemKind::Impl(hir::Impl { unsafety, @@ -754,7 +772,7 @@ impl<'a> State<'a> { for impl_item in items { self.ann.nested(self, Nested::ImplItem(impl_item.id)); } - self.bclose(item.span); + self.bclose(self.span(item.hir_id())); } hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => { self.head(""); @@ -781,7 +799,7 @@ impl<'a> State<'a> { for trait_item in trait_items { self.ann.nested(self, Nested::TraitItem(trait_item.id)); } - self.bclose(item.span); + self.bclose(self.span(item.hir_id())); } hir::ItemKind::TraitAlias(ref generics, ref bounds) => { self.head(""); @@ -964,7 +982,7 @@ impl<'a> State<'a> { pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) { self.ann.pre(self, AnnNode::SubItem(ti.hir_id())); self.hardbreak_if_not_bol(); - self.maybe_print_comment(ti.span.lo()); + self.maybe_print_comment(self.span(ti.hir_id()).lo()); self.print_outer_attributes(self.attrs(ti.hir_id())); match ti.kind { hir::TraitItemKind::Const(ref ty, default) => { @@ -1003,7 +1021,7 @@ impl<'a> State<'a> { pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) { self.ann.pre(self, AnnNode::SubItem(ii.hir_id())); self.hardbreak_if_not_bol(); - self.maybe_print_comment(ii.span.lo()); + self.maybe_print_comment(self.span(ii.hir_id()).lo()); self.print_outer_attributes(self.attrs(ii.hir_id())); self.print_defaultness(ii.defaultness); diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index d4fdbe8263b97..b1119c28bb665 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -734,11 +734,12 @@ impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations { return; } let param_env = ty::ParamEnv::empty(); - if ty.is_copy_modulo_regions(cx.tcx.at(item.span), param_env) { + let item_span = cx.tcx.hir().span_with_body(item.hir_id()); + if ty.is_copy_modulo_regions(cx.tcx.at(item_span), param_env) { return; } if can_type_implement_copy(cx.tcx, param_env, ty).is_ok() { - cx.struct_span_lint(MISSING_COPY_IMPLEMENTATIONS, item.span, |lint| { + cx.struct_span_lint(MISSING_COPY_IMPLEMENTATIONS, item_span, |lint| { lint.build( "type could implement `Copy`; consider adding `impl \ Copy`", @@ -819,7 +820,8 @@ impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations { } if !self.impling_types.as_ref().unwrap().contains(&item.def_id) { - cx.struct_span_lint(MISSING_DEBUG_IMPLEMENTATIONS, item.span, |lint| { + let item_span = cx.tcx.hir().span_with_body(item.hir_id()); + cx.struct_span_lint(MISSING_DEBUG_IMPLEMENTATIONS, item_span, |lint| { lint.build(&format!( "type does not implement `{}`; consider adding `#[derive(Debug)]` \ or a manual implementation", @@ -1103,7 +1105,8 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { match param.kind { GenericParamKind::Lifetime { .. } => {} GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { - cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS, it.span, |lint| { + let it_span = cx.tcx.hir().span_with_body(it.hir_id()); + cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS, it_span, |lint| { lint.build( "functions generic over types or consts must be mangled", ) @@ -1127,7 +1130,8 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { if cx.sess().contains_name(attrs, sym::no_mangle) { // Const items do not refer to a particular location in memory, and therefore // don't have anything to attach a symbol to - cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, |lint| { + let it_span = cx.tcx.hir().span_with_body(it.hir_id()); + cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it_span, |lint| { let msg = "const items should never be `#[no_mangle]`"; let mut err = lint.build(msg); @@ -1136,11 +1140,11 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { .tcx .sess .source_map() - .span_to_snippet(it.span) + .span_to_snippet(it_span) .map(|snippet| snippet.find("const").unwrap_or(0)) .unwrap_or(0) as u32; // `const` is 5 chars - let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5)); + let const_span = it_span.with_hi(BytePos(it_span.lo().0 + start + 5)); err.span_suggestion( const_span, "try a static value", diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 9336add96929c..602b8970eb47e 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1058,11 +1058,14 @@ impl EncodeContext<'a, 'tcx> { let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); let ast_item = tcx.hir().expect_trait_item(hir_id); let trait_item = tcx.associated_item(def_id); + let ast_item_span = tcx.hir().span_with_body(hir_id); let container = match trait_item.defaultness { hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault, hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired, - hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"), + hir::Defaultness::Final => { + span_bug!(ast_item_span, "traits cannot have final items") + } }; match trait_item.kind { @@ -1131,19 +1134,20 @@ impl EncodeContext<'a, 'tcx> { let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); let ast_item = self.tcx.hir().expect_impl_item(hir_id); let impl_item = self.tcx.associated_item(def_id); + let ast_item_span = tcx.hir().span_with_body(hir_id); let container = match impl_item.defaultness { hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault, hir::Defaultness::Final => AssocContainer::ImplFinal, hir::Defaultness::Default { has_value: false } => { - span_bug!(ast_item.span, "impl items always have values (currently)") + span_bug!(ast_item_span, "impl items always have values (currently)") } }; match impl_item.kind { ty::AssocKind::Const => { if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind { - let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id); + let qualifs = self.tcx.at(ast_item_span).mir_const_qualif(def_id); record!(self.tables.kind[def_id] <- EntryKind::AssocConst( container, @@ -1301,7 +1305,8 @@ impl EncodeContext<'a, 'tcx> { hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic, hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic, hir::ItemKind::Const(_, body_id) => { - let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id); + let item_span = tcx.hir().span_with_body(item.hir_id()); + let qualifs = self.tcx.at(item_span).mir_const_qualif(def_id); EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id)) } hir::ItemKind::Fn(ref sig, .., body) => { @@ -1378,7 +1383,8 @@ impl EncodeContext<'a, 'tcx> { // "unsized info", else just store None let coerce_unsized_info = trait_ref.and_then(|t| { if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() { - Some(self.tcx.at(item.span).coerce_unsized_info(def_id)) + let item_span = tcx.hir().span_with_body(item.hir_id()); + Some(self.tcx.at(item_span).coerce_unsized_info(def_id)) } else { None } diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index 5a63253e1723e..f9a94287fc39c 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -51,22 +51,20 @@ fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam) -> Body<'_ } Node::Item(hir::Item { kind: hir::ItemKind::Fn(hir::FnSig { decl, .. }, _, body_id), - span, .. }) | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(hir::FnSig { decl, .. }, body_id), - span, .. }) | Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(hir::FnSig { decl, .. }, hir::TraitFn::Provided(body_id)), - span, .. }) => { // Use the `Span` of the `Item/ImplItem/TraitItem` as the body span, // since the def span of a function does not include the body - (*body_id, decl.output.span(), Some(*span)) + let span = tcx.hir().span_with_body(id); + (*body_id, decl.output.span(), Some(span)) } Node::Item(hir::Item { kind: hir::ItemKind::Static(ty, _, body_id) | hir::ItemKind::Const(ty, body_id), diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 3e6592ef0775d..316b58e914a54 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -596,6 +596,7 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> { fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { if self.should_warn_about_item(item) { // For most items, we want to highlight its identifier + let item_span = self.tcx.hir().span_with_body(item.hir_id()); let span = match item.kind { hir::ItemKind::Fn(..) | hir::ItemKind::Mod(..) @@ -610,13 +611,13 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> { // (and thus has a source_callee set). // We should probably annotate ident.span with the macro // context, but that's a larger change. - if item.span.source_callee().is_some() { - self.tcx.sess.source_map().guess_head_span(item.span) + if item_span.source_callee().is_some() { + self.tcx.sess.source_map().guess_head_span(item_span) } else { item.ident.span } } - _ => item.span, + _ => item_span, }; let participle = match item.kind { hir::ItemKind::Struct(..) => "constructed", // Issue #52325 @@ -662,9 +663,10 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> { match impl_item.kind { hir::ImplItemKind::Const(_, body_id) => { if !self.symbol_is_live(impl_item.hir_id()) { + let impl_item_span = self.tcx.hir().span_with_body(impl_item.hir_id()); self.warn_dead_code( impl_item.hir_id(), - impl_item.span, + impl_item_span, impl_item.ident.name, "used", ); @@ -679,8 +681,9 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> { // (and thus has a source_callee set). // We should probably annotate ident.span with the macro // context, but that's a larger change. - let span = if impl_item.span.source_callee().is_some() { - self.tcx.sess.source_map().guess_head_span(impl_item.span) + let impl_item_span = self.tcx.hir().span_with_body(impl_item.hir_id()); + let span = if impl_item_span.source_callee().is_some() { + self.tcx.sess.source_map().guess_head_span(impl_item_span) } else { impl_item.ident.span }; diff --git a/compiler/rustc_passes/src/layout_test.rs b/compiler/rustc_passes/src/layout_test.rs index 18c1d647060b1..9028563acbb06 100644 --- a/compiler/rustc_passes/src/layout_test.rs +++ b/compiler/rustc_passes/src/layout_test.rs @@ -46,6 +46,7 @@ impl LayoutTest<'tcx> { let tcx = self.tcx; let param_env = self.tcx.param_env(item_def_id); let ty = self.tcx.type_of(item_def_id); + let item_span = tcx.hir().span_with_body(item.hir_id()); match self.tcx.layout_of(param_env.and(ty)) { Ok(ty_layout) => { // Check out the `#[rustc_layout(..)]` attribute to tell what to dump. @@ -54,24 +55,24 @@ impl LayoutTest<'tcx> { for meta_item in meta_items { match meta_item.name_or_empty() { sym::abi => { - self.tcx.sess.span_err(item.span, &format!("abi: {:?}", ty_layout.abi)); + self.tcx.sess.span_err(item_span, &format!("abi: {:?}", ty_layout.abi)); } sym::align => { self.tcx .sess - .span_err(item.span, &format!("align: {:?}", ty_layout.align)); + .span_err(item_span, &format!("align: {:?}", ty_layout.align)); } sym::size => { self.tcx .sess - .span_err(item.span, &format!("size: {:?}", ty_layout.size)); + .span_err(item_span, &format!("size: {:?}", ty_layout.size)); } sym::homogeneous_aggregate => { self.tcx.sess.span_err( - item.span, + item_span, &format!( "homogeneous_aggregate: {:?}", ty_layout @@ -86,7 +87,7 @@ impl LayoutTest<'tcx> { ty, ); self.tcx.sess.span_err( - item.span, + item_span, &format!("layout_of({:?}) = {:#?}", normalized_ty, *ty_layout), ); } @@ -102,7 +103,7 @@ impl LayoutTest<'tcx> { } Err(layout_error) => { - self.tcx.sess.span_err(item.span, &format!("layout error: {:?}", layout_error)); + self.tcx.sess.span_err(item_span, &format!("layout error: {:?}", layout_error)); } } } diff --git a/compiler/rustc_passes/src/reachable.rs b/compiler/rustc_passes/src/reachable.rs index 20aaaea5b9809..46b9e7813bce0 100644 --- a/compiler/rustc_passes/src/reachable.rs +++ b/compiler/rustc_passes/src/reachable.rs @@ -55,7 +55,10 @@ fn method_might_be_inlined( } match tcx.hir().find(tcx.hir().local_def_id_to_hir_id(impl_src)) { Some(Node::Item(item)) => item_might_be_inlined(tcx, &item, codegen_fn_attrs), - Some(..) | None => span_bug!(impl_item.span, "impl did is not an item"), + Some(..) | None => { + let impl_item_span = tcx.hir().span_with_body(impl_item.hir_id()); + span_bug!(impl_item_span, "impl did is not an item") + } } } diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index acf749cbdd85a..b33e4b496c474 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -721,7 +721,8 @@ impl Visitor<'tcx> for Checker<'tcx> { hir::ItemKind::ExternCrate(_) => { // compiler-generated `extern crate` items have a dummy span. // `std` is still checked for the `restricted-std` feature. - if item.span.is_dummy() && item.ident.as_str() != "std" { + let item_span = self.tcx.hir().span_with_body(item.hir_id()); + if item_span.is_dummy() && item.ident.as_str() != "std" { return; } @@ -730,7 +731,7 @@ impl Visitor<'tcx> for Checker<'tcx> { None => return, }; let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX }; - self.tcx.check_stability(def_id, Some(item.hir_id()), item.span); + self.tcx.check_stability(def_id, Some(item.hir_id()), item_span); } // For implementations of traits, check the stability of each item @@ -743,8 +744,9 @@ impl Visitor<'tcx> for Checker<'tcx> { // it will have no effect. // See: https://github.com/rust-lang/rust/issues/55436 let attrs = self.tcx.hir().attrs(item.hir_id()); + let item_span = self.tcx.hir().span_with_body(item.hir_id()); if let (Some((Stability { level: attr::Unstable { .. }, .. }, span)), _) = - attr::find_stability(&self.tcx.sess, attrs, item.span) + attr::find_stability(&self.tcx.sess, attrs, item_span) { let mut c = CheckTraitImplStable { tcx: self.tcx, fully_stable: true }; c.visit_ty(self_ty); @@ -774,7 +776,8 @@ impl Visitor<'tcx> for Checker<'tcx> { .map(|item| item.def_id); if let Some(def_id) = trait_item_def_id { // Pass `None` to skip deprecation warnings. - self.tcx.check_stability(def_id, None, impl_item.span); + let impl_item_span = self.tcx.hir().span_with_body(impl_item.hir_id()); + self.tcx.check_stability(def_id, None, impl_item_span); } } } @@ -799,8 +802,9 @@ impl Visitor<'tcx> for Checker<'tcx> { if field_ty.needs_drop(self.tcx, param_env) { // Avoid duplicate error: This will error later anyway because fields // that need drop are not allowed. + let item_span = self.tcx.hir().span_with_body(item.hir_id()); self.tcx.sess.delay_span_bug( - item.span, + item_span, "union should have been rejected due to potentially dropping field", ); } else { diff --git a/compiler/rustc_plugin_impl/src/build.rs b/compiler/rustc_plugin_impl/src/build.rs index a49afa35e4624..61d29764cedf9 100644 --- a/compiler/rustc_plugin_impl/src/build.rs +++ b/compiler/rustc_plugin_impl/src/build.rs @@ -6,11 +6,10 @@ use rustc_hir::itemlikevisit::ItemLikeVisitor; use rustc_middle::ty::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_span::symbol::sym; -use rustc_span::Span; struct RegistrarFinder<'tcx> { tcx: TyCtxt<'tcx>, - registrars: Vec<(LocalDefId, Span)>, + registrars: Vec, } impl<'v, 'tcx> ItemLikeVisitor<'v> for RegistrarFinder<'tcx> { @@ -18,7 +17,7 @@ impl<'v, 'tcx> ItemLikeVisitor<'v> for RegistrarFinder<'tcx> { if let hir::ItemKind::Fn(..) = item.kind { let attrs = self.tcx.hir().attrs(item.hir_id()); if self.tcx.sess.contains_name(attrs, sym::plugin_registrar) { - self.registrars.push((item.def_id, item.span)); + self.registrars.push(item.def_id); } } } @@ -44,13 +43,14 @@ fn plugin_registrar_fn(tcx: TyCtxt<'_>, cnum: CrateNum) -> Option { match finder.registrars.len() { 0 => None, 1 => { - let (def_id, _) = finder.registrars.pop().unwrap(); + let def_id = finder.registrars.pop().unwrap(); Some(def_id.to_def_id()) } _ => { let diagnostic = tcx.sess.diagnostic(); let mut e = diagnostic.struct_err("multiple plugin registration functions found"); - for &(_, span) in &finder.registrars { + for &def_id in &finder.registrars { + let span = tcx.hir().span_with_body(tcx.hir().local_def_id_to_hir_id(def_id)); e.span_note(span, "one is here"); } e.emit(); diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index d3a818cc32cdb..b22b311bafe39 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -2065,7 +2065,10 @@ fn visibility(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Visibility { }, |def_id| tcx.visibility(def_id), ), - _ => span_bug!(impl_item.span, "the parent is not a trait impl"), + _ => { + let impl_item_span = tcx.hir().span(impl_item.hir_id()); + span_bug!(impl_item_span, "the parent is not a trait impl") + } } } _ => span_bug!( diff --git a/compiler/rustc_resolve/src/late/lifetimes.rs b/compiler/rustc_resolve/src/late/lifetimes.rs index 70cf28442321a..0b5de2f55b9d2 100644 --- a/compiler/rustc_resolve/src/late/lifetimes.rs +++ b/compiler/rustc_resolve/src/late/lifetimes.rs @@ -1268,7 +1268,8 @@ fn compute_object_lifetime_defaults(tcx: TyCtxt<'_>) -> HirIdMap>>() .join(","); - tcx.sess.span_err(item.span, &object_lifetime_default_reprs); + let item_span = tcx.hir().span_with_body(item.hir_id()); + tcx.sess.span_err(item_span, &object_lifetime_default_reprs); } map.insert(item.hir_id(), result); 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 49a3f64988661..d912bdcfb7b25 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -803,18 +803,20 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { }) .collect::>>()?, ), - Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. }) + Node::Item(&hir::Item { def_id, kind: hir::ItemKind::Fn(ref sig, ..), .. }) | Node::ImplItem(&hir::ImplItem { - span, + def_id, kind: hir::ImplItemKind::Fn(ref sig, _), .. }) | Node::TraitItem(&hir::TraitItem { - span, + def_id, kind: hir::TraitItemKind::Fn(ref sig, _), .. }) => ( - sm.guess_head_span(span), + sm.guess_head_span( + self.tcx.hir().span_with_body(self.tcx.hir().local_def_id_to_hir_id(def_id)), + ), sig.decl .inputs .iter() diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index 29f1761b84d2b..abdb023f5da31 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -154,8 +154,9 @@ fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem { _ => {} } + let parent_item_span = tcx.hir().span_with_body(parent_item.hir_id()); span_bug!( - parent_item.span, + parent_item_span, "unexpected parent of trait or impl item or item not found: {:?}", parent_item.kind ) @@ -206,7 +207,10 @@ fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] { impl_.items.iter().map(|impl_item_ref| impl_item_ref.id.def_id.to_def_id()), ), hir::ItemKind::TraitAlias(..) => &[], - _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"), + _ => { + let item_span = tcx.hir().span_with_body(item.hir_id()); + span_bug!(item_span, "associated_item_def_ids: not impl or trait") + } } } diff --git a/compiler/rustc_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index a0c3c03d79bcb..f29d6cfd04463 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -750,11 +750,12 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { let assoc_item = tcx.associated_item(item.def_id); let trait_substs = InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id()); + let item_span = tcx.hir().span_with_body(item.hir_id()); let _: Result<_, rustc_errors::ErrorReported> = check_type_bounds( tcx, assoc_item, assoc_item, - item.span, + item_span, ty::TraitRef { def_id: it.def_id.to_def_id(), substs: trait_substs }, ); } @@ -917,7 +918,7 @@ fn check_impl_items_against_trait<'tcx>( impl_trait_ref: ty::TraitRef<'tcx>, impl_item_refs: &[hir::ImplItemRef<'_>], ) { - let full_impl_span = tcx.def_span(impl_id); + let full_impl_span = tcx.hir().span_with_body(tcx.hir().local_def_id_to_hir_id(impl_id)); // If the trait reference itself is erroneous (so the compilation is going // to fail), skip checking the items here -- the `impl_item` table in `tcx` @@ -931,7 +932,7 @@ fn check_impl_items_against_trait<'tcx>( ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {} ty::ImplPolarity::Negative => { if let [first_item_ref, ..] = impl_item_refs { - let first_item_span = tcx.hir().impl_item(first_item_ref.id).span; + let first_item_span = tcx.hir().span_with_body(first_item_ref.id.hir_id()); struct_span_err!( tcx.sess, first_item_span, @@ -953,6 +954,7 @@ fn check_impl_items_against_trait<'tcx>( // and compatible with trait signature for impl_item in impl_items { let ty_impl_item = tcx.associated_item(impl_item.def_id); + let impl_item_span = tcx.hir().span_with_body(impl_item.hir_id()); let mut items = associated_items.filter_by_name(tcx, ty_impl_item.ident, impl_trait_ref.def_id); @@ -989,7 +991,7 @@ fn check_impl_items_against_trait<'tcx>( compare_const_impl( tcx, &ty_impl_item, - impl_item.span, + impl_item_span, &ty_trait_item, impl_trait_ref, ); @@ -999,7 +1001,7 @@ fn check_impl_items_against_trait<'tcx>( compare_impl_method( tcx, &ty_impl_item, - impl_item.span, + impl_item_span, &ty_trait_item, impl_trait_ref, opt_trait_span, @@ -1010,7 +1012,7 @@ fn check_impl_items_against_trait<'tcx>( compare_ty_impl( tcx, &ty_impl_item, - impl_item.span, + impl_item_span, &ty_trait_item, impl_trait_ref, opt_trait_span, @@ -1069,12 +1071,13 @@ fn report_mismatch_error<'tcx>( impl_item: &hir::ImplItem<'_>, ty_impl_item: &ty::AssocItem, ) { + let impl_item_span = tcx.hir().span_with_body(impl_item.hir_id()); let mut err = match impl_item.kind { hir::ImplItemKind::Const(..) => { // Find associated const definition. struct_span_err!( tcx.sess, - impl_item.span, + impl_item_span, E0323, "item `{}` is an associated const, which doesn't match its trait `{}`", ty_impl_item.ident, @@ -1085,7 +1088,7 @@ fn report_mismatch_error<'tcx>( hir::ImplItemKind::Fn(..) => { struct_span_err!( tcx.sess, - impl_item.span, + impl_item_span, E0324, "item `{}` is an associated method, which doesn't match its trait `{}`", ty_impl_item.ident, @@ -1096,7 +1099,7 @@ fn report_mismatch_error<'tcx>( hir::ImplItemKind::TyAlias(_) => { struct_span_err!( tcx.sess, - impl_item.span, + impl_item_span, E0325, "item `{}` is an associated type, which doesn't match its trait `{}`", ty_impl_item.ident, @@ -1105,7 +1108,7 @@ fn report_mismatch_error<'tcx>( } }; - err.span_label(impl_item.span, "does not match trait"); + err.span_label(impl_item_span, "does not match trait"); if let Some(trait_span) = tcx.hir().span_if_local(trait_item_def_id) { err.span_label(trait_span, "item in trait"); } diff --git a/compiler/rustc_typeck/src/check/method/suggest.rs b/compiler/rustc_typeck/src/check/method/suggest.rs index a7cbf67673186..125daf80f8dc7 100644 --- a/compiler/rustc_typeck/src/check/method/suggest.rs +++ b/compiler/rustc_typeck/src/check/method/suggest.rs @@ -1449,12 +1449,13 @@ impl intravisit::Visitor<'tcx> for UsePlacementFinder<'tcx> { // Find a `use` statement. for &item_id in module.item_ids { let item = self.tcx.hir().item(item_id); + let item_span = self.tcx.hir().span_with_body(item.hir_id()); match item.kind { hir::ItemKind::Use(..) => { // Don't suggest placing a `use` before the prelude // import or other generated ones. - if !item.span.from_expansion() { - self.span = Some(item.span.shrink_to_lo()); + if !item_span.from_expansion() { + self.span = Some(item_span.shrink_to_lo()); self.found_use = true; return; } @@ -1463,12 +1464,12 @@ impl intravisit::Visitor<'tcx> for UsePlacementFinder<'tcx> { hir::ItemKind::ExternCrate(_) => {} // ...but do place them before the first other item. _ => { - if self.span.map_or(true, |span| item.span < span) { - if !item.span.from_expansion() { + if self.span.map_or(true, |span| item_span < span) { + if !item_span.from_expansion() { // Don't insert between attributes and an item. let attrs = self.tcx.hir().attrs(item.hir_id()); if attrs.is_empty() { - self.span = Some(item.span.shrink_to_lo()); + self.span = Some(item_span.shrink_to_lo()); } else { // Find the first attribute on the item. for attr in attrs { diff --git a/compiler/rustc_typeck/src/check/mod.rs b/compiler/rustc_typeck/src/check/mod.rs index 80cac7bee0841..ebebc8de6c209 100644 --- a/compiler/rustc_typeck/src/check/mod.rs +++ b/compiler/rustc_typeck/src/check/mod.rs @@ -788,15 +788,16 @@ fn report_forbidden_specialization( impl_item: &hir::ImplItem<'_>, parent_impl: DefId, ) { + let impl_item_span = tcx.hir().span_with_body(impl_item.hir_id()); let mut err = struct_span_err!( tcx.sess, - impl_item.span, + impl_item_span, E0520, "`{}` specializes an item from a parent `impl`, but \ that item is not marked `default`", impl_item.ident ); - err.span_label(impl_item.span, format!("cannot specialize default item `{}`", impl_item.ident)); + err.span_label(impl_item_span, format!("cannot specialize default item `{}`", impl_item.ident)); match tcx.span_of_impl(parent_impl) { Ok(span) => { diff --git a/compiler/rustc_typeck/src/check/wfcheck.rs b/compiler/rustc_typeck/src/check/wfcheck.rs index 9f09100b59dc3..97c1a64c80366 100644 --- a/compiler/rustc_typeck/src/check/wfcheck.rs +++ b/compiler/rustc_typeck/src/check/wfcheck.rs @@ -108,7 +108,8 @@ pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) { .impl_trait_ref(item.def_id) .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id)); if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) { - let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span); + let item_span = tcx.hir().span_with_body(item.hir_id()); + let sp = impl_.of_trait.as_ref().map_or(item_span, |t| t.path.span); let mut err = tcx.sess.struct_span_err(sp, "impls of auto traits cannot be default"); err.span_labels(impl_.defaultness_span, "default because of this"); @@ -141,7 +142,7 @@ pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) { } } hir::ItemKind::Fn(ref sig, ..) => { - check_item_fn(tcx, item.hir_id(), item.ident, item.span, sig.decl); + check_item_fn(tcx, item.hir_id(), item.ident, sig.decl); } hir::ItemKind::Static(ref ty, ..) => { check_item_type(tcx, item.hir_id(), ty.span, false); @@ -154,7 +155,7 @@ pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) { let it = tcx.hir().foreign_item(it.id); match it.kind { hir::ForeignItemKind::Fn(ref decl, ..) => { - check_item_fn(tcx, it.hir_id(), it.ident, it.span, decl) + check_item_fn(tcx, it.hir_id(), it.ident, decl) } hir::ForeignItemKind::Static(ref ty, ..) => { check_item_type(tcx, it.hir_id(), ty.span, true) @@ -197,7 +198,7 @@ pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: LocalDefId) { _ => None, }; check_object_unsafe_self_trait_by_name(tcx, &trait_item); - check_associated_item(tcx, trait_item.hir_id(), trait_item.span, method_sig); + check_associated_item(tcx, trait_item.hir_id(), method_sig); } fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool { @@ -271,7 +272,7 @@ pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: LocalDefId) { _ => None, }; - check_associated_item(tcx, impl_item.hir_id(), impl_item.span, method_sig); + check_associated_item(tcx, impl_item.hir_id(), method_sig); } fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) { @@ -379,12 +380,12 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) { fn check_associated_item( tcx: TyCtxt<'_>, item_id: hir::HirId, - span: Span, sig_if_method: Option<&hir::FnSig<'_>>, ) { debug!("check_associated_item: {:?}", item_id); let code = ObligationCauseCode::MiscObligation; + let span = tcx.hir().span_with_body(item_id); for_id(tcx, item_id, span).with_fcx(|fcx, tcx| { let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id(item_id)); @@ -433,7 +434,8 @@ fn check_associated_item( } fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>) -> CheckWfFcxBuilder<'tcx> { - for_id(tcx, item.hir_id(), item.span) + let item_span = tcx.hir().span_with_body(item.hir_id()); + for_id(tcx, item.hir_id(), item_span) } fn for_id(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) -> CheckWfFcxBuilder<'_> { @@ -476,9 +478,10 @@ fn check_type_defn<'tcx, F>( let ty = variant.fields.last().unwrap().ty; let ty = fcx.tcx.erase_regions(ty); if ty.needs_infer() { + let item_span = tcx.hir().span_with_body(item.hir_id()); fcx_tcx .sess - .delay_span_bug(item.span, &format!("inference variables in {:?}", ty)); + .delay_span_bug(item_span, &format!("inference variables in {:?}", ty)); // Just treat unresolved type expression as if it needs drop. true } else { @@ -541,7 +544,8 @@ fn check_type_defn<'tcx, F>( } } - check_where_clauses(tcx, fcx, item.span, item.def_id.to_def_id(), None); + let item_span = tcx.hir().span_with_body(item.hir_id()); + check_where_clauses(tcx, fcx, item_span, item.def_id.to_def_id(), None); // No implied bounds in a struct definition. vec![] @@ -567,7 +571,8 @@ fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) { } for_item(tcx, item).with_fcx(|fcx, _| { - check_where_clauses(tcx, fcx, item.span, item.def_id.to_def_id(), None); + let item_span = tcx.hir().span_with_body(item.hir_id()); + check_where_clauses(tcx, fcx, item_span, item.def_id.to_def_id(), None); vec![] }); @@ -600,13 +605,8 @@ fn check_associated_type_bounds(fcx: &FnCtxt<'_, '_>, item: &ty::AssocItem, span } } -fn check_item_fn( - tcx: TyCtxt<'_>, - item_id: hir::HirId, - ident: Ident, - span: Span, - decl: &hir::FnDecl<'_>, -) { +fn check_item_fn(tcx: TyCtxt<'_>, item_id: hir::HirId, ident: Ident, decl: &hir::FnDecl<'_>) { + let span = tcx.hir().span_with_body(item_id); for_id(tcx, item_id, span).with_fcx(|fcx, tcx| { let def_id = fcx.tcx.hir().local_def_id(item_id); let sig = fcx.tcx.fn_sig(def_id); @@ -685,7 +685,8 @@ fn check_impl<'tcx>( } None => { let self_ty = fcx.tcx.type_of(item.def_id); - let self_ty = fcx.normalize_associated_types_in(item.span, self_ty); + let item_span = tcx.hir().span_with_body(item.hir_id()); + let self_ty = fcx.normalize_associated_types_in(item_span, self_ty); fcx.register_wf_obligation( self_ty.into(), ast_self_ty.span, @@ -694,9 +695,10 @@ fn check_impl<'tcx>( } } - check_where_clauses(tcx, fcx, item.span, item.def_id.to_def_id(), None); + let item_span = tcx.hir().span_with_body(item.hir_id()); + check_where_clauses(tcx, fcx, item_span, item.def_id.to_def_id(), None); - fcx.impl_implied_bounds(item.def_id.to_def_id(), item.span) + fcx.impl_implied_bounds(item.def_id.to_def_id(), item_span) }); } diff --git a/compiler/rustc_typeck/src/check_unused.rs b/compiler/rustc_typeck/src/check_unused.rs index e1743a5dfc1ce..4c39efb76ede9 100644 --- a/compiler/rustc_typeck/src/check_unused.rs +++ b/compiler/rustc_typeck/src/check_unused.rs @@ -24,7 +24,8 @@ pub fn check_crate(tcx: TyCtxt<'_>) { impl ItemLikeVisitor<'v> for CheckVisitor<'tcx> { fn visit_item(&mut self, item: &hir::Item<'_>) { - if item.vis.node.is_pub() || item.span.is_dummy() { + let item_span = self.tcx.hir().span_with_body(item.hir_id()); + if item.vis.node.is_pub() || item_span.is_dummy() { return; } if let hir::ItemKind::Use(ref path, _) = item.kind { @@ -113,6 +114,7 @@ fn unused_crates_lint(tcx: TyCtxt<'_>) { // Collect all the extern crates (in a reliable order). let mut crates_to_lint = vec![]; tcx.hir().krate().visit_all_item_likes(&mut CollectExternCrateVisitor { + tcx, crates_to_lint: &mut crates_to_lint, }); @@ -192,7 +194,8 @@ fn unused_crates_lint(tcx: TyCtxt<'_>) { } } -struct CollectExternCrateVisitor<'a> { +struct CollectExternCrateVisitor<'a, 'tcx> { + tcx: TyCtxt<'tcx>, crates_to_lint: &'a mut Vec, } @@ -213,12 +216,13 @@ struct ExternCrateToLint { warn_if_unused: bool, } -impl<'a, 'v> ItemLikeVisitor<'v> for CollectExternCrateVisitor<'a> { +impl<'a, 'v, 'tcx> ItemLikeVisitor<'v> for CollectExternCrateVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &hir::Item<'_>) { if let hir::ItemKind::ExternCrate(orig_name) = item.kind { + let item_span = self.tcx.hir().span_with_body(item.hir_id()); self.crates_to_lint.push(ExternCrateToLint { def_id: item.def_id.to_def_id(), - span: item.span, + span: item_span, orig_name, warn_if_unused: !item.ident.as_str().starts_with('_'), }); diff --git a/compiler/rustc_typeck/src/coherence/inherent_impls.rs b/compiler/rustc_typeck/src/coherence/inherent_impls.rs index cc592c7a260f1..b831b9da58f57 100644 --- a/compiler/rustc_typeck/src/coherence/inherent_impls.rs +++ b/compiler/rustc_typeck/src/coherence/inherent_impls.rs @@ -52,6 +52,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { let self_ty = self.tcx.type_of(item.def_id); let lang_items = self.tcx.lang_items(); + let item_span = self.tcx.hir().span_with_body(item.hir_id()); match *self_ty.kind() { ty::Adt(def, _) => { self.check_def_id(item, def.did); @@ -69,7 +70,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "bool", "bool", - item.span, + item_span, assoc_items, ); } @@ -80,7 +81,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "char", "char", - item.span, + item_span, assoc_items, ); } @@ -91,7 +92,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { lang_items.str_alloc_impl(), "str", "str", - item.span, + item_span, assoc_items, ); } @@ -102,7 +103,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { lang_items.slice_u8_alloc_impl(), "slice_u8", "[u8]", - item.span, + item_span, assoc_items, ); } @@ -113,7 +114,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { lang_items.slice_alloc_impl(), "slice", "[T]", - item.span, + item_span, assoc_items, ); } @@ -124,7 +125,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "array", "[T; N]", - item.span, + item_span, assoc_items, ); } @@ -137,7 +138,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "const_slice_ptr", "*const [T]", - item.span, + item_span, assoc_items, ); } @@ -150,7 +151,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "mut_slice_ptr", "*mut [T]", - item.span, + item_span, assoc_items, ); } @@ -161,7 +162,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "const_ptr", "*const T", - item.span, + item_span, assoc_items, ); } @@ -172,7 +173,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "mut_ptr", "*mut T", - item.span, + item_span, assoc_items, ); } @@ -183,7 +184,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "i8", "i8", - item.span, + item_span, assoc_items, ); } @@ -194,7 +195,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "i16", "i16", - item.span, + item_span, assoc_items, ); } @@ -205,7 +206,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "i32", "i32", - item.span, + item_span, assoc_items, ); } @@ -216,7 +217,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "i64", "i64", - item.span, + item_span, assoc_items, ); } @@ -227,7 +228,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "i128", "i128", - item.span, + item_span, assoc_items, ); } @@ -238,7 +239,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "isize", "isize", - item.span, + item_span, assoc_items, ); } @@ -249,7 +250,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "u8", "u8", - item.span, + item_span, assoc_items, ); } @@ -260,7 +261,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "u16", "u16", - item.span, + item_span, assoc_items, ); } @@ -271,7 +272,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "u32", "u32", - item.span, + item_span, assoc_items, ); } @@ -282,7 +283,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "u64", "u64", - item.span, + item_span, assoc_items, ); } @@ -293,7 +294,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "u128", "u128", - item.span, + item_span, assoc_items, ); } @@ -304,7 +305,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "usize", "usize", - item.span, + item_span, assoc_items, ); } @@ -315,7 +316,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { lang_items.f32_runtime_impl(), "f32", "f32", - item.span, + item_span, assoc_items, ); } @@ -326,7 +327,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { lang_items.f64_runtime_impl(), "f64", "f64", - item.span, + item_span, assoc_items, ); } @@ -371,14 +372,15 @@ impl InherentCollect<'tcx> { let vec = self.impls_map.inherent_impls.entry(def_id).or_default(); vec.push(item.def_id.to_def_id()); } else { + let item_span = self.tcx.hir().span_with_body(item.hir_id()); struct_span_err!( self.tcx.sess, - item.span, + item_span, E0116, "cannot define inherent `impl` for a type outside of the crate \ where the type is defined" ) - .span_label(item.span, "impl for type defined outside of crate.") + .span_label(item_span, "impl for type defined outside of crate.") .note("define and implement a trait or new type instead") .emit(); } diff --git a/compiler/rustc_typeck/src/coherence/orphan.rs b/compiler/rustc_typeck/src/coherence/orphan.rs index 96721e92e6877..02e5b6613f9d6 100644 --- a/compiler/rustc_typeck/src/coherence/orphan.rs +++ b/compiler/rustc_typeck/src/coherence/orphan.rs @@ -35,8 +35,9 @@ impl ItemLikeVisitor<'v> for OrphanChecker<'tcx> { ); let trait_ref = self.tcx.impl_trait_ref(item.def_id).unwrap(); let trait_def_id = trait_ref.def_id; + let item_span = self.tcx.hir().span_with_body(item.hir_id()); let sm = self.tcx.sess.source_map(); - let sp = sm.guess_head_span(item.span); + let sp = sm.guess_head_span(item_span); match traits::orphan_check(self.tcx, item.def_id.to_def_id()) { Ok(()) => {} Err(traits::OrphanCheckErr::NonLocalInputType(tys)) => { diff --git a/compiler/rustc_typeck/src/coherence/unsafety.rs b/compiler/rustc_typeck/src/coherence/unsafety.rs index 6b995b9738612..7449b2bfb4a46 100644 --- a/compiler/rustc_typeck/src/coherence/unsafety.rs +++ b/compiler/rustc_typeck/src/coherence/unsafety.rs @@ -25,6 +25,7 @@ impl UnsafetyChecker<'tcx> { polarity: hir::ImplPolarity, ) { if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id) { + let item_span = self.tcx.hir().span_with_body(item.hir_id()); let trait_def = self.tcx.trait_def(trait_ref.def_id); let unsafe_attr = impl_generics.and_then(|generics| { generics.params.iter().find(|p| p.pure_wrt_drop).map(|_| "may_dangle") @@ -33,7 +34,7 @@ impl UnsafetyChecker<'tcx> { (Unsafety::Normal, None, Unsafety::Unsafe, hir::ImplPolarity::Positive) => { struct_span_err!( self.tcx.sess, - item.span, + item_span, E0199, "implementing the trait `{}` is not unsafe", trait_ref.print_only_trait_path() @@ -44,7 +45,7 @@ impl UnsafetyChecker<'tcx> { (Unsafety::Unsafe, _, Unsafety::Normal, hir::ImplPolarity::Positive) => { struct_span_err!( self.tcx.sess, - item.span, + item_span, E0200, "the trait `{}` requires an `unsafe impl` declaration", trait_ref.print_only_trait_path() @@ -60,7 +61,7 @@ impl UnsafetyChecker<'tcx> { ) => { struct_span_err!( self.tcx.sess, - item.span, + item_span, E0569, "requires an `unsafe impl` declaration due to `#[{}]` attribute", attr_name @@ -70,7 +71,7 @@ impl UnsafetyChecker<'tcx> { (_, _, Unsafety::Unsafe, hir::ImplPolarity::Negative(_)) => { // Reported in AST validation - self.tcx.sess.delay_span_bug(item.span, "unsafe negative impl"); + self.tcx.sess.delay_span_bug(item_span, "unsafe negative impl"); } (_, _, Unsafety::Normal, hir::ImplPolarity::Negative(_)) | (Unsafety::Unsafe, _, Unsafety::Unsafe, hir::ImplPolarity::Positive) diff --git a/compiler/rustc_typeck/src/collect.rs b/compiler/rustc_typeck/src/collect.rs index ca2f16bb31922..b59a12ae9dc19 100644 --- a/compiler/rustc_typeck/src/collect.rs +++ b/compiler/rustc_typeck/src/collect.rs @@ -587,8 +587,9 @@ fn type_param_predicates( // Implied `Self: Trait` and supertrait bounds. if param_id == item_hir_id { let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id); + let item_span = tcx.hir().span_with_body(item.hir_id()); extend = - Some((identity_trait_ref.without_const().to_predicate(tcx), item.span)); + Some((identity_trait_ref.without_const().to_predicate(tcx), item_span)); } generics } @@ -752,12 +753,14 @@ fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) { hir::ItemKind::Trait(..) => { tcx.ensure().generics_of(def_id); tcx.ensure().trait_def(def_id); - tcx.at(it.span).super_predicates_of(def_id); + let it_span = tcx.hir().span_with_body(it.hir_id()); + tcx.at(it_span).super_predicates_of(def_id); tcx.ensure().predicates_of(def_id); } hir::ItemKind::TraitAlias(..) => { tcx.ensure().generics_of(def_id); - tcx.at(it.span).super_predicates_of(def_id); + let it_span = tcx.hir().span_with_body(it.hir_id()); + tcx.at(it_span).super_predicates_of(def_id); tcx.ensure().predicates_of(def_id); } hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { @@ -1086,11 +1089,14 @@ fn super_predicates_that_define_assoc_type( Node::Item(item) => item, _ => bug!("trait_node_id {} is not an item", trait_hir_id), }; + let item_span = tcx.hir().span_with_body(item.hir_id()); let (generics, bounds) = match item.kind { hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits), hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits), - _ => span_bug!(item.span, "super_predicates invoked on non-trait"), + _ => { + span_bug!(item_span, "super_predicates invoked on non-trait") + } }; let icx = ItemCtxt::new(tcx, trait_def_id); @@ -1103,11 +1109,11 @@ fn super_predicates_that_define_assoc_type( self_param_ty, &bounds, SizedByDefault::No, - item.span, + item_span, assoc_name, ) } else { - AstConv::compute_bounds(&icx, self_param_ty, &bounds, SizedByDefault::No, item.span) + AstConv::compute_bounds(&icx, self_param_ty, &bounds, SizedByDefault::No, item_span) }; let superbounds1 = superbounds1.predicates(tcx, self_param_ty); @@ -1158,14 +1164,18 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef { let (is_auto, unsafety) = match item.kind { hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety), hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal), - _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"), + _ => { + let item_span = tcx.hir().span_with_body(item.hir_id()); + span_bug!(item_span, "trait_def_of_item invoked on non-trait") + } }; let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar); if paren_sugar && !tcx.features().unboxed_closures { + let item_span = tcx.hir().span_with_body(item.hir_id()); tcx.sess .struct_span_err( - item.span, + item_span, "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \ which traits can use parenthetical notation", ) @@ -1799,7 +1809,8 @@ fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity { .. }) => { if is_rustc_reservation { - tcx.sess.span_err(item.span, "reservation impls can't be inherent"); + let item_span = tcx.hir().span_with_body(item.hir_id()); + tcx.sess.span_err(item_span, "reservation impls can't be inherent"); } ty::ImplPolarity::Positive } diff --git a/compiler/rustc_typeck/src/collect/item_bounds.rs b/compiler/rustc_typeck/src/collect/item_bounds.rs index fe18dc5ed0c69..ad7518128547e 100644 --- a/compiler/rustc_typeck/src/collect/item_bounds.rs +++ b/compiler/rustc_typeck/src/collect/item_bounds.rs @@ -86,17 +86,15 @@ pub(super) fn explicit_item_bounds( def_id: DefId, ) -> &'_ [(ty::Predicate<'_>, Span)] { let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); + let span = tcx.hir().span_with_body(hir_id); match tcx.hir().get(hir_id) { hir::Node::TraitItem(hir::TraitItem { - kind: hir::TraitItemKind::Type(bounds, _), - span, - .. - }) => associated_type_bounds(tcx, def_id, bounds, *span), + kind: hir::TraitItemKind::Type(bounds, _), .. + }) => associated_type_bounds(tcx, def_id, bounds, span), hir::Node::Item(hir::Item { kind: hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds, .. }), - span, .. - }) => opaque_type_bounds(tcx, def_id, bounds, *span), + }) => opaque_type_bounds(tcx, def_id, bounds, span), _ => bug!("item_bounds called on {:?}", def_id), } } diff --git a/compiler/rustc_typeck/src/collect/type_of.rs b/compiler/rustc_typeck/src/collect/type_of.rs index 3f2f244e44fd2..fd66bf949aaed 100644 --- a/compiler/rustc_typeck/src/collect/type_of.rs +++ b/compiler/rustc_typeck/src/collect/type_of.rs @@ -275,7 +275,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { .unwrap_or_else(|| icx.to_ty(ty)), TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty), TraitItemKind::Type(_, None) => { - span_bug!(item.span, "associated type missing default"); + let item_span = tcx.hir().span_with_body(item.hir_id()); + span_bug!(item_span, "associated type missing default"); } }, @@ -293,7 +294,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { } ImplItemKind::TyAlias(ref ty) => { if tcx.impl_trait_ref(tcx.hir().get_parent_did(hir_id).to_def_id()).is_none() { - check_feature_inherent_assoc_ty(tcx, item.span); + let item_span = tcx.hir().span_with_body(item.hir_id()); + check_feature_inherent_assoc_ty(tcx, item_span); } icx.to_ty(ty) @@ -368,8 +370,9 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { | ItemKind::GlobalAsm(..) | ItemKind::ExternCrate(..) | ItemKind::Use(..) => { + let item_span = tcx.hir().span_with_body(item.hir_id()); span_bug!( - item.span, + item_span, "compute_type_of_item: unexpected item type: {:?}", item.kind ); diff --git a/compiler/rustc_typeck/src/impl_wf_check.rs b/compiler/rustc_typeck/src/impl_wf_check.rs index 7713381e62e46..22edfc911182a 100644 --- a/compiler/rustc_typeck/src/impl_wf_check.rs +++ b/compiler/rustc_typeck/src/impl_wf_check.rs @@ -84,7 +84,8 @@ impl ItemLikeVisitor<'tcx> for ImplWfCheck<'tcx> { enforce_impl_params_are_constrained(self.tcx, item.def_id, impl_.items); enforce_impl_items_are_distinct(self.tcx, impl_.items); if self.min_specialization { - check_min_specialization(self.tcx, item.def_id.to_def_id(), item.span); + let item_span = self.tcx.hir().span_with_body(item.hir_id()); + check_min_specialization(self.tcx, item.def_id.to_def_id(), item_span); } } } @@ -239,11 +240,12 @@ fn enforce_impl_items_are_distinct(tcx: TyCtxt<'_>, impl_item_refs: &[hir::ImplI hir::ImplItemKind::TyAlias(_) => &mut seen_type_items, _ => &mut seen_value_items, }; + let impl_item_span = tcx.hir().span_with_body(impl_item.hir_id()); match seen_items.entry(impl_item.ident.normalize_to_macros_2_0()) { Occupied(entry) => { let mut err = struct_span_err!( tcx.sess, - impl_item.span, + impl_item_span, E0201, "duplicate definitions with name `{}`:", impl_item.ident @@ -252,11 +254,11 @@ fn enforce_impl_items_are_distinct(tcx: TyCtxt<'_>, impl_item_refs: &[hir::ImplI *entry.get(), format!("previous definition of `{}` here", impl_item.ident), ); - err.span_label(impl_item.span, "duplicate definition"); + err.span_label(impl_item_span, "duplicate definition"); err.emit(); } Vacant(entry) => { - entry.insert(impl_item.span); + entry.insert(impl_item_span); } } } diff --git a/compiler/rustc_typeck/src/lib.rs b/compiler/rustc_typeck/src/lib.rs index 29d9df61906c7..03736aa2c1d51 100644 --- a/compiler/rustc_typeck/src/lib.rs +++ b/compiler/rustc_typeck/src/lib.rs @@ -194,7 +194,8 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: LocalDefId) { error = true; } if let hir::IsAsync::Async = sig.header.asyncness { - let span = tcx.sess.source_map().guess_head_span(it.span); + let it_span = tcx.hir().span_with_body(it.hir_id()); + let span = tcx.sess.source_map().guess_head_span(it_span); struct_span_err!( tcx.sess, span, @@ -294,7 +295,8 @@ fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: LocalDefId) { error = true; } if let hir::IsAsync::Async = sig.header.asyncness { - let span = tcx.sess.source_map().guess_head_span(it.span); + let it_span = tcx.hir().span_with_body(it.hir_id()); + let span = tcx.sess.source_map().guess_head_span(it_span); struct_span_err!( tcx.sess, span, diff --git a/compiler/rustc_typeck/src/outlives/test.rs b/compiler/rustc_typeck/src/outlives/test.rs index d4bef0c409a8f..c9c1445726fd5 100644 --- a/compiler/rustc_typeck/src/outlives/test.rs +++ b/compiler/rustc_typeck/src/outlives/test.rs @@ -18,7 +18,8 @@ impl ItemLikeVisitor<'tcx> for OutlivesTest<'tcx> { // attribute and report an error with various results if found. if self.tcx.has_attr(item.def_id.to_def_id(), sym::rustc_outlives) { let inferred_outlives_of = self.tcx.inferred_outlives_of(item.def_id); - struct_span_err!(self.tcx.sess, item.span, E0640, "{:?}", inferred_outlives_of).emit(); + let item_span = self.tcx.hir().span_with_body(item.hir_id()); + struct_span_err!(self.tcx.sess, item_span, E0640, "{:?}", inferred_outlives_of).emit(); } } diff --git a/compiler/rustc_typeck/src/variance/test.rs b/compiler/rustc_typeck/src/variance/test.rs index 2a0d950c87dab..c857c195c9ae9 100644 --- a/compiler/rustc_typeck/src/variance/test.rs +++ b/compiler/rustc_typeck/src/variance/test.rs @@ -18,7 +18,8 @@ impl ItemLikeVisitor<'tcx> for VarianceTest<'tcx> { // attribute and report an error with various results if found. if self.tcx.has_attr(item.def_id.to_def_id(), sym::rustc_variance) { let variances_of = self.tcx.variances_of(item.def_id); - struct_span_err!(self.tcx.sess, item.span, E0208, "{:?}", variances_of).emit(); + let item_span = self.tcx.hir().span_with_body(item.hir_id()); + struct_span_err!(self.tcx.sess, item_span, E0208, "{:?}", variances_of).emit(); } } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 539895feddd42..cd4f50b0f178b 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2132,7 +2132,7 @@ fn clean_extern_crate( vec![Item { name: Some(name), attrs: box attrs.clean(cx), - source: krate.span.clean(cx), + source: cx.tcx.hir().span(hir::CRATE_HIR_ID).clean(cx), def_id: crate_def_id, visibility: krate.vis.clean(cx), kind: box ExternCrateItem { src: orig_name }, @@ -2149,7 +2149,9 @@ fn clean_use_statement( // We need this comparison because some imports (for std types for example) // are "inserted" as well but directly by the compiler and they should not be // taken into account. - if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) { + if cx.tcx.hir().span_with_body(import.hir_id()).ctxt().outer_expn_data().kind + == ExpnKind::AstPass(AstPass::StdImports) + { return Vec::new(); } @@ -2165,7 +2167,7 @@ fn clean_use_statement( E0780, "anonymous imports cannot be inlined" ) - .span_label(import.span, "anonymous import") + .span_label(cx.tcx.hir().span_with_body(import.hir_id()), "anonymous import") .emit(); } } diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 3217c7bc3574c..7541eaa2f8aee 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -1054,19 +1054,22 @@ impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> item.ident.to_string() }; - self.visit_testable(name, item.hir_id(), item.span, |this| { + let item_span = self.tcx.hir().span(item.hir_id()); + self.visit_testable(name, item.hir_id(), item_span, |this| { intravisit::walk_item(this, item); }); } fn visit_trait_item(&mut self, item: &'hir hir::TraitItem<'_>) { - self.visit_testable(item.ident.to_string(), item.hir_id(), item.span, |this| { + let item_span = self.tcx.hir().span(item.hir_id()); + self.visit_testable(item.ident.to_string(), item.hir_id(), item_span, |this| { intravisit::walk_trait_item(this, item); }); } fn visit_impl_item(&mut self, item: &'hir hir::ImplItem<'_>) { - self.visit_testable(item.ident.to_string(), item.hir_id(), item.span, |this| { + let item_span = self.tcx.hir().span(item.hir_id()); + self.visit_testable(item.ident.to_string(), item.hir_id(), item_span, |this| { intravisit::walk_impl_item(this, item); }); } diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 675345a8824bb..aff5c87908c52 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -313,7 +313,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { } hir::ItemKind::Mod(ref m) => { om.mods.push(self.visit_mod_contents( - item.span, + self.cx.tcx.hir().span_with_body(item.hir_id()), &item.vis, item.hir_id(), m, diff --git a/src/tools/clippy/clippy_lints/src/attrs.rs b/src/tools/clippy/clippy_lints/src/attrs.rs index 6250810bc4277..6305977777db2 100644 --- a/src/tools/clippy/clippy_lints/src/attrs.rs +++ b/src/tools/clippy/clippy_lints/src/attrs.rs @@ -278,7 +278,7 @@ impl<'tcx> LateLintPass<'tcx> for Attributes { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { let attrs = cx.tcx.hir().attrs(item.hir_id()); if is_relevant_item(cx, item) { - check_attrs(cx, item.span, item.ident.name, attrs) + check_attrs(cx, cx.tcx.hir().span(item.hir_id()), item.ident.name, attrs) } match item.kind { ItemKind::ExternCrate(..) | ItemKind::Use(..) => { @@ -354,13 +354,23 @@ impl<'tcx> LateLintPass<'tcx> for Attributes { fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) { if is_relevant_impl(cx, item) { - check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id())) + check_attrs( + cx, + cx.tcx.hir().span(item.hir_id()), + item.ident.name, + cx.tcx.hir().attrs(item.hir_id()), + ) } } fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) { if is_relevant_trait(cx, item) { - check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id())) + check_attrs( + cx, + cx.tcx.hir().span(item.hir_id()), + item.ident.name, + cx.tcx.hir().attrs(item.hir_id()), + ) } } } diff --git a/src/tools/clippy/clippy_lints/src/copy_iterator.rs b/src/tools/clippy/clippy_lints/src/copy_iterator.rs index 004bce5f62a8f..be9a6342e0cf0 100644 --- a/src/tools/clippy/clippy_lints/src/copy_iterator.rs +++ b/src/tools/clippy/clippy_lints/src/copy_iterator.rs @@ -44,7 +44,7 @@ impl<'tcx> LateLintPass<'tcx> for CopyIterator { span_lint_and_note( cx, COPY_ITERATOR, - item.span, + cx.tcx.hir().span_with_body(item.hir_id()), "you are implementing `Iterator` on a `Copy` type", None, "consider implementing `IntoIterator` instead", diff --git a/src/tools/clippy/clippy_lints/src/derive.rs b/src/tools/clippy/clippy_lints/src/derive.rs index ead1453e9d003..4eabdbf95b557 100644 --- a/src/tools/clippy/clippy_lints/src/derive.rs +++ b/src/tools/clippy/clippy_lints/src/derive.rs @@ -173,8 +173,9 @@ impl<'tcx> LateLintPass<'tcx> for Derive { let attrs = cx.tcx.hir().attrs(item.hir_id()); let is_automatically_derived = is_automatically_derived(attrs); - check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived); - check_ord_partial_ord(cx, item.span, trait_ref, ty, is_automatically_derived); + let item_span = cx.tcx.hir().span_with_body(item.hir_id()); + check_hash_peq(cx, item_span, trait_ref, ty, is_automatically_derived); + check_ord_partial_ord(cx, item_span, trait_ref, ty, is_automatically_derived); if is_automatically_derived { check_unsafe_derive_deserialize(cx, item, trait_ref, ty); @@ -327,12 +328,13 @@ fn check_copy_clone<'tcx>(cx: &LateContext<'tcx>, item: &Item<'_>, trait_ref: &T _ => (), } + let item_span = cx.tcx.hir().span_with_body(item.hir_id()); span_lint_and_note( cx, EXPL_IMPL_CLONE_ON_COPY, - item.span, + item_span, "you are implementing `Clone` explicitly on a `Copy` type", - Some(item.span), + Some(item_span), "consider deriving `Clone` or removing `Copy`", ); } @@ -371,7 +373,7 @@ fn check_unsafe_derive_deserialize<'tcx>( span_lint_and_help( cx, UNSAFE_DERIVE_DESERIALIZE, - item.span, + cx.tcx.hir().span_with_body(item.hir_id()), "you are deriving `serde::Deserialize` on a type that has methods using `unsafe`", None, "consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html" diff --git a/src/tools/clippy/clippy_lints/src/doc.rs b/src/tools/clippy/clippy_lints/src/doc.rs index 90b02d52f8a71..6c13c737808ea 100644 --- a/src/tools/clippy/clippy_lints/src/doc.rs +++ b/src/tools/clippy/clippy_lints/src/doc.rs @@ -218,7 +218,8 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { let headers = check_attrs(cx, &self.valid_idents, attrs); match item.kind { hir::ItemKind::Fn(ref sig, _, body_id) => { - if !(is_entrypoint_fn(cx, item.def_id.to_def_id()) || in_external_macro(cx.tcx.sess, item.span)) { + let item_span = cx.tcx.hir().span_with_body(item.hir_id()); + if !(is_entrypoint_fn(cx, item.def_id.to_def_id()) || in_external_macro(cx.tcx.sess, item_span)) { let body = cx.tcx.hir().body(body_id); let mut fpu = FindPanicUnwrap { cx, @@ -229,7 +230,7 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { lint_for_missing_headers( cx, item.hir_id(), - item.span, + item_span, sig, headers, Some(body_id), @@ -254,16 +255,18 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { let attrs = cx.tcx.hir().attrs(item.hir_id()); let headers = check_attrs(cx, &self.valid_idents, attrs); if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind { - if !in_external_macro(cx.tcx.sess, item.span) { - lint_for_missing_headers(cx, item.hir_id(), item.span, sig, headers, None, None); + let item_span = cx.tcx.hir().span_with_body(item.hir_id()); + if !in_external_macro(cx.tcx.sess, item_span) { + lint_for_missing_headers(cx, item.hir_id(), item_span, sig, headers, None, None); } } } fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) { let attrs = cx.tcx.hir().attrs(item.hir_id()); + let item_span = cx.tcx.hir().span_with_body(item.hir_id()); let headers = check_attrs(cx, &self.valid_idents, attrs); - if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) { + if self.in_trait_impl || in_external_macro(cx.tcx.sess, item_span) { return; } if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind { @@ -277,7 +280,7 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { lint_for_missing_headers( cx, item.hir_id(), - item.span, + item_span, sig, headers, Some(body_id), diff --git a/src/tools/clippy/clippy_lints/src/empty_enum.rs b/src/tools/clippy/clippy_lints/src/empty_enum.rs index 077c3b75fb8c8..69393dc2ad3e4 100644 --- a/src/tools/clippy/clippy_lints/src/empty_enum.rs +++ b/src/tools/clippy/clippy_lints/src/empty_enum.rs @@ -56,7 +56,7 @@ impl<'tcx> LateLintPass<'tcx> for EmptyEnum { span_lint_and_help( cx, EMPTY_ENUM, - item.span, + cx.tcx.hir().span_with_body(item.hir_id()), "enum with no variants", None, "consider using the uninhabited type `!` (never type) or a wrapper \ diff --git a/src/tools/clippy/clippy_lints/src/exhaustive_items.rs b/src/tools/clippy/clippy_lints/src/exhaustive_items.rs index 316f748486280..e716f1ca28eeb 100644 --- a/src/tools/clippy/clippy_lints/src/exhaustive_items.rs +++ b/src/tools/clippy/clippy_lints/src/exhaustive_items.rs @@ -85,12 +85,13 @@ impl LateLintPass<'_> for ExhaustiveItems { } else { (EXHAUSTIVE_ENUMS, "exported enums should not be exhaustive") }; - let suggestion_span = item.span.shrink_to_lo(); - let indent = " ".repeat(indent_of(cx, item.span).unwrap_or(0)); + let item_span = cx.tcx.hir().span_with_body(item.hir_id()); + let suggestion_span = item_span.shrink_to_lo(); + let indent = " ".repeat(indent_of(cx, item_span).unwrap_or(0)); span_lint_and_then( cx, lint, - item.span, + item_span, msg, |diag| { let sugg = format!("#[non_exhaustive]\n{}", indent); diff --git a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs index f466dddc13c20..bf854c94b6700 100644 --- a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs +++ b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs @@ -57,7 +57,7 @@ impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom { if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.def_id); if cx.tcx.is_diagnostic_item(sym::from_trait, impl_trait_ref.def_id); then { - lint_impl_body(cx, item.span, impl_.items); + lint_impl_body(cx, cx.tcx.hir().span_with_body(item.hir_id()), impl_.items); } } } diff --git a/src/tools/clippy/clippy_lints/src/from_over_into.rs b/src/tools/clippy/clippy_lints/src/from_over_into.rs index b644bb079908f..c30554e67da67 100644 --- a/src/tools/clippy/clippy_lints/src/from_over_into.rs +++ b/src/tools/clippy/clippy_lints/src/from_over_into.rs @@ -69,7 +69,7 @@ impl LateLintPass<'_> for FromOverInto { span_lint_and_help( cx, FROM_OVER_INTO, - cx.tcx.sess.source_map().guess_head_span(item.span), + cx.tcx.sess.source_map().guess_head_span(cx.tcx.hir().span(item.hir_id())), "an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true", None, "consider to implement `From` instead", diff --git a/src/tools/clippy/clippy_lints/src/functions.rs b/src/tools/clippy/clippy_lints/src/functions.rs index e04a58647361b..a1c2779a6e0f5 100644 --- a/src/tools/clippy/clippy_lints/src/functions.rs +++ b/src/tools/clippy/clippy_lints/src/functions.rs @@ -285,12 +285,13 @@ impl<'tcx> LateLintPass<'tcx> for Functions { let attr = must_use_attr(attrs); if let hir::ItemKind::Fn(ref sig, ref _generics, ref body_id) = item.kind { let is_public = cx.access_levels.is_exported(item.hir_id()); - let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); + let item_span = cx.tcx.hir().span_with_body(item.hir_id()); + let fn_header_span = item_span.with_hi(sig.decl.output.span().hi()); if is_public { - check_result_unit_err(cx, &sig.decl, item.span, fn_header_span); + check_result_unit_err(cx, &sig.decl, item_span, fn_header_span); } if let Some(attr) = attr { - check_needless_must_use(cx, &sig.decl, item.hir_id(), item.span, fn_header_span, attr); + check_needless_must_use(cx, &sig.decl, item.hir_id(), item_span, fn_header_span, attr); return; } if is_public && !is_proc_macro(cx.sess(), attrs) && attr_by_name(attrs, "no_mangle").is_none() { @@ -298,9 +299,9 @@ impl<'tcx> LateLintPass<'tcx> for Functions { cx, &sig.decl, cx.tcx.hir().body(*body_id), - item.span, + item_span, item.hir_id(), - item.span.with_hi(sig.decl.output.span().hi()), + item_span.with_hi(sig.decl.output.span().hi()), "this function could have a `#[must_use]` attribute", ); } @@ -310,23 +311,31 @@ impl<'tcx> LateLintPass<'tcx> for Functions { fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) { if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind { let is_public = cx.access_levels.is_exported(item.hir_id()); - let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); + let item_span = cx.tcx.hir().span_with_body(item.hir_id()); + let fn_header_span = item_span.with_hi(sig.decl.output.span().hi()); if is_public && trait_ref_of_method(cx, item.hir_id()).is_none() { - check_result_unit_err(cx, &sig.decl, item.span, fn_header_span); + check_result_unit_err(cx, &sig.decl, item_span, fn_header_span); } let attrs = cx.tcx.hir().attrs(item.hir_id()); let attr = must_use_attr(attrs); if let Some(attr) = attr { - check_needless_must_use(cx, &sig.decl, item.hir_id(), item.span, fn_header_span, attr); + check_needless_must_use( + cx, + &sig.decl, + item.hir_id(), + cx.tcx.hir().span_with_body(item.hir_id()), + fn_header_span, + attr, + ); } else if is_public && !is_proc_macro(cx.sess(), attrs) && trait_ref_of_method(cx, item.hir_id()).is_none() { check_must_use_candidate( cx, &sig.decl, cx.tcx.hir().body(*body_id), - item.span, + item_span, item.hir_id(), - item.span.with_hi(sig.decl.output.span().hi()), + item_span.with_hi(sig.decl.output.span().hi()), "this method could have a `#[must_use]` attribute", ); } @@ -335,20 +344,22 @@ impl<'tcx> LateLintPass<'tcx> for Functions { fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) { if let hir::TraitItemKind::Fn(ref sig, ref eid) = item.kind { + let item_span = cx.tcx.hir().span_with_body(item.hir_id()); + // don't lint extern functions decls, it's not their fault if sig.header.abi == Abi::Rust { - self.check_arg_number(cx, &sig.decl, item.span.with_hi(sig.decl.output.span().hi())); + self.check_arg_number(cx, &sig.decl, item_span.with_hi(sig.decl.output.span().hi())); } let is_public = cx.access_levels.is_exported(item.hir_id()); - let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); + let fn_header_span = item_span.with_hi(sig.decl.output.span().hi()); if is_public { - check_result_unit_err(cx, &sig.decl, item.span, fn_header_span); + check_result_unit_err(cx, &sig.decl, item_span, fn_header_span); } let attrs = cx.tcx.hir().attrs(item.hir_id()); let attr = must_use_attr(attrs); if let Some(attr) = attr { - check_needless_must_use(cx, &sig.decl, item.hir_id(), item.span, fn_header_span, attr); + check_needless_must_use(cx, &sig.decl, item.hir_id(), item_span, fn_header_span, attr); } if let hir::TraitFn::Provided(eid) = *eid { let body = cx.tcx.hir().body(eid); @@ -359,9 +370,9 @@ impl<'tcx> LateLintPass<'tcx> for Functions { cx, &sig.decl, body, - item.span, + item_span, item.hir_id(), - item.span.with_hi(sig.decl.output.span().hi()), + item_span.with_hi(sig.decl.output.span().hi()), "this method could have a `#[must_use]` attribute", ); } diff --git a/src/tools/clippy/clippy_lints/src/inherent_impl.rs b/src/tools/clippy/clippy_lints/src/inherent_impl.rs index 005c461f105e6..d71c79d5c93ef 100644 --- a/src/tools/clippy/clippy_lints/src/inherent_impl.rs +++ b/src/tools/clippy/clippy_lints/src/inherent_impl.rs @@ -48,7 +48,7 @@ pub struct MultipleInherentImpl { impl_lint_pass!(MultipleInherentImpl => [MULTIPLE_INHERENT_IMPL]); impl<'tcx> LateLintPass<'tcx> for MultipleInherentImpl { - fn check_item(&mut self, _: &LateContext<'tcx>, item: &'tcx Item<'_>) { + fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { if let ItemKind::Impl(Impl { ref generics, of_trait: None, @@ -58,8 +58,9 @@ impl<'tcx> LateLintPass<'tcx> for MultipleInherentImpl { // Remember for each inherent implementation encountered its span and generics // but filter out implementations that have generic params (type or lifetime) // or are derived from a macro - if !in_macro(item.span) && generics.params.is_empty() { - self.impls.insert(item.def_id.to_def_id(), item.span); + let item_span = cx.tcx.hir().span_with_body(item.hir_id()); + if !in_macro(item_span) && generics.params.is_empty() { + self.impls.insert(item.def_id.to_def_id(), item_span); } } } diff --git a/src/tools/clippy/clippy_lints/src/inherent_to_string.rs b/src/tools/clippy/clippy_lints/src/inherent_to_string.rs index c1f3e1d9d685c..f4788778845a1 100644 --- a/src/tools/clippy/clippy_lints/src/inherent_to_string.rs +++ b/src/tools/clippy/clippy_lints/src/inherent_to_string.rs @@ -95,7 +95,7 @@ declare_lint_pass!(InherentToString => [INHERENT_TO_STRING, INHERENT_TO_STRING_S impl<'tcx> LateLintPass<'tcx> for InherentToString { fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>) { - if impl_item.span.from_expansion() { + if cx.tcx.hir().span_with_body(impl_item.hir_id()).from_expansion() { return; } @@ -133,7 +133,7 @@ fn show_lint(cx: &LateContext<'_>, item: &ImplItem<'_>) { span_lint_and_help( cx, INHERENT_TO_STRING_SHADOW_DISPLAY, - item.span, + cx.tcx.hir().span_with_body(item.hir_id()), &format!( "type `{}` implements inherent method `to_string(&self) -> String` which shadows the implementation of `Display`", self_type.to_string() @@ -145,7 +145,7 @@ fn show_lint(cx: &LateContext<'_>, item: &ImplItem<'_>) { span_lint_and_help( cx, INHERENT_TO_STRING, - item.span, + cx.tcx.hir().span_with_body(item.hir_id()), &format!( "implementation of inherent method `to_string(&self) -> String` for type `{}`", self_type.to_string() diff --git a/src/tools/clippy/clippy_lints/src/large_const_arrays.rs b/src/tools/clippy/clippy_lints/src/large_const_arrays.rs index a76595ed0897d..bab0ef79ab47a 100644 --- a/src/tools/clippy/clippy_lints/src/large_const_arrays.rs +++ b/src/tools/clippy/clippy_lints/src/large_const_arrays.rs @@ -47,8 +47,9 @@ impl_lint_pass!(LargeConstArrays => [LARGE_CONST_ARRAYS]); impl<'tcx> LateLintPass<'tcx> for LargeConstArrays { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { + let item_span = cx.tcx.hir().span_with_body(item.hir_id()); if_chain! { - if !item.span.from_expansion(); + if !item_span.from_expansion(); if let ItemKind::Const(hir_ty, _) = &item.kind; let ty = hir_ty_to_ty(cx.tcx, hir_ty); if let ty::Array(element_type, cst) = ty.kind(); @@ -62,12 +63,12 @@ impl<'tcx> LateLintPass<'tcx> for LargeConstArrays { let sugg_span = Span::new( hi_pos - BytePos::from_usize("const".len()), hi_pos, - item.span.ctxt(), + item_span.ctxt(), ); span_lint_and_then( cx, LARGE_CONST_ARRAYS, - item.span, + item_span, "large array defined as const", |diag| { diag.span_suggestion( 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 c76490c69ded1..8d0d329319854 100644 --- a/src/tools/clippy/clippy_lints/src/large_enum_variant.rs +++ b/src/tools/clippy/clippy_lints/src/large_enum_variant.rs @@ -59,7 +59,7 @@ impl_lint_pass!(LargeEnumVariant => [LARGE_ENUM_VARIANT]); impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { - if in_external_macro(cx.tcx.sess, item.span) { + if in_external_macro(cx.tcx.sess, cx.tcx.hir().span(item.hir_id())) { return; } if let ItemKind::Enum(ref def, _) = item.kind { diff --git a/src/tools/clippy/clippy_lints/src/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs index 1e1023b274350..c1d121b60b6a6 100644 --- a/src/tools/clippy/clippy_lints/src/len_zero.rs +++ b/src/tools/clippy/clippy_lints/src/len_zero.rs @@ -115,7 +115,7 @@ declare_lint_pass!(LenZero => [LEN_ZERO, LEN_WITHOUT_IS_EMPTY, COMPARISON_TO_EMP impl<'tcx> LateLintPass<'tcx> for LenZero { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { - if item.span.from_expansion() { + if cx.tcx.hir().span_with_body(item.hir_id()).from_expansion() { return; } @@ -222,7 +222,7 @@ fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items span_lint( cx, LEN_WITHOUT_IS_EMPTY, - visited_trait.span, + cx.tcx.hir().span_with_body(visited_trait.hir_id()), &format!( "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method", visited_trait.ident.name diff --git a/src/tools/clippy/clippy_lints/src/lifetimes.rs b/src/tools/clippy/clippy_lints/src/lifetimes.rs index cb0838221c765..a259e299c02d4 100644 --- a/src/tools/clippy/clippy_lints/src/lifetimes.rs +++ b/src/tools/clippy/clippy_lints/src/lifetimes.rs @@ -80,7 +80,14 @@ declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]); impl<'tcx> LateLintPass<'tcx> for Lifetimes { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { if let ItemKind::Fn(ref sig, ref generics, id) = item.kind { - check_fn_inner(cx, &sig.decl, Some(id), generics, item.span, true); + check_fn_inner( + cx, + &sig.decl, + Some(id), + generics, + cx.tcx.hir().span_with_body(item.hir_id()), + true, + ); } } @@ -92,7 +99,7 @@ impl<'tcx> LateLintPass<'tcx> for Lifetimes { &sig.decl, Some(id), &item.generics, - item.span, + cx.tcx.hir().span_with_body(item.hir_id()), report_extra_lifetimes, ); } @@ -104,7 +111,14 @@ impl<'tcx> LateLintPass<'tcx> for Lifetimes { TraitFn::Required(_) => None, TraitFn::Provided(id) => Some(id), }; - check_fn_inner(cx, &sig.decl, body, &item.generics, item.span, true); + check_fn_inner( + cx, + &sig.decl, + body, + &item.generics, + cx.tcx.hir().span_with_body(item.hir_id()), + true, + ); } } } diff --git a/src/tools/clippy/clippy_lints/src/macro_use.rs b/src/tools/clippy/clippy_lints/src/macro_use.rs index 229f3003e8786..a1f91587a5b43 100644 --- a/src/tools/clippy/clippy_lints/src/macro_use.rs +++ b/src/tools/clippy/clippy_lints/src/macro_use.rs @@ -121,8 +121,9 @@ impl<'tcx> LateLintPass<'tcx> for MacroUseImports { } } } else { - if in_macro(item.span) { - self.push_unique_macro_pat_ty(cx, item.span); + let item_span = cx.tcx.hir().span(item.hir_id()); + if in_macro(item_span) { + self.push_unique_macro_pat_ty(cx, item_span); } } } diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index 86c951d024ce1..fdc8f76630851 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -1826,7 +1826,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { #[allow(clippy::too_many_lines)] fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) { - if in_external_macro(cx.sess(), impl_item.span) { + if in_external_macro(cx.sess(), cx.tcx.hir().span_with_body(impl_item.hir_id())) { return; } let name = impl_item.ident.name.as_str(); @@ -1862,10 +1862,11 @@ impl<'tcx> LateLintPass<'tcx> for Methods { fn_header_equals(method_config.fn_header, sig.header) && method_config.lifetime_param_cond(&impl_item) { + let impl_item_span = cx.tcx.hir().span_with_body(impl_item.hir_id()); span_lint_and_help( cx, SHOULD_IMPLEMENT_TRAIT, - impl_item.span, + impl_item_span, &format!( "method `{}` can be confused for the standard trait method `{}::{}`", method_config.method_name, @@ -1918,7 +1919,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { span_lint( cx, NEW_RET_NO_SELF, - impl_item.span, + cx.tcx.hir().span_with_body(impl_item.hir_id()), "methods called `new` usually return `Self`", ); } @@ -1926,7 +1927,8 @@ impl<'tcx> LateLintPass<'tcx> for Methods { } fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) { - if in_external_macro(cx.tcx.sess, item.span) { + let item_span = cx.tcx.hir().span_with_body(item.hir_id()); + if in_external_macro(cx.tcx.sess, item_span) { return; } @@ -1960,7 +1962,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { span_lint( cx, NEW_RET_NO_SELF, - item.span, + item_span, "methods called `new` usually return `Self`", ); } diff --git a/src/tools/clippy/clippy_lints/src/missing_doc.rs b/src/tools/clippy/clippy_lints/src/missing_doc.rs index 49bdde15a92c8..107b633098f1f 100644 --- a/src/tools/clippy/clippy_lints/src/missing_doc.rs +++ b/src/tools/clippy/clippy_lints/src/missing_doc.rs @@ -163,14 +163,20 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { let (article, desc) = cx.tcx.article_and_description(it.def_id.to_def_id()); let attrs = cx.tcx.hir().attrs(it.hir_id()); - self.check_missing_docs_attrs(cx, attrs, it.span, article, desc); + self.check_missing_docs_attrs(cx, attrs, cx.tcx.hir().span_with_body(it.hir_id()), article, desc); } fn check_trait_item(&mut self, cx: &LateContext<'tcx>, trait_item: &'tcx hir::TraitItem<'_>) { let (article, desc) = cx.tcx.article_and_description(trait_item.def_id.to_def_id()); let attrs = cx.tcx.hir().attrs(trait_item.hir_id()); - self.check_missing_docs_attrs(cx, attrs, trait_item.span, article, desc); + self.check_missing_docs_attrs( + cx, + attrs, + cx.tcx.hir().span_with_body(trait_item.hir_id()), + article, + desc, + ); } fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) { @@ -186,7 +192,13 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { let (article, desc) = cx.tcx.article_and_description(impl_item.def_id.to_def_id()); let attrs = cx.tcx.hir().attrs(impl_item.hir_id()); - self.check_missing_docs_attrs(cx, attrs, impl_item.span, article, desc); + self.check_missing_docs_attrs( + cx, + attrs, + cx.tcx.hir().span_with_body(impl_item.hir_id()), + article, + desc, + ); } fn check_struct_field(&mut self, cx: &LateContext<'tcx>, sf: &'tcx hir::StructField<'_>) { diff --git a/src/tools/clippy/clippy_lints/src/missing_inline.rs b/src/tools/clippy/clippy_lints/src/missing_inline.rs index da59c820999d9..a049c7f1736c6 100644 --- a/src/tools/clippy/clippy_lints/src/missing_inline.rs +++ b/src/tools/clippy/clippy_lints/src/missing_inline.rs @@ -83,7 +83,9 @@ declare_lint_pass!(MissingInline => [MISSING_INLINE_IN_PUBLIC_ITEMS]); impl<'tcx> LateLintPass<'tcx> for MissingInline { fn check_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx hir::Item<'_>) { - if rustc_middle::lint::in_external_macro(cx.sess(), it.span) || is_executable_or_proc_macro(cx) { + if rustc_middle::lint::in_external_macro(cx.sess(), cx.tcx.hir().span_with_body(it.hir_id())) + || is_executable_or_proc_macro(cx) + { return; } @@ -94,7 +96,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { hir::ItemKind::Fn(..) => { let desc = "a function"; let attrs = cx.tcx.hir().attrs(it.hir_id()); - check_missing_inline_attrs(cx, attrs, it.span, desc); + check_missing_inline_attrs(cx, attrs, cx.tcx.hir().span_with_body(it.hir_id()), desc); }, hir::ItemKind::Trait(ref _is_auto, ref _unsafe, ref _generics, ref _bounds, trait_items) => { // note: we need to check if the trait is exported so we can't use @@ -110,7 +112,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { let desc = "a default trait method"; let item = cx.tcx.hir().trait_item(tit.id); let attrs = cx.tcx.hir().attrs(item.hir_id()); - check_missing_inline_attrs(cx, attrs, item.span, desc); + check_missing_inline_attrs(cx, attrs, cx.tcx.hir().span_with_body(item.hir_id()), desc); } }, } @@ -135,7 +137,9 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) { use rustc_middle::ty::{ImplContainer, TraitContainer}; - if rustc_middle::lint::in_external_macro(cx.sess(), impl_item.span) || is_executable_or_proc_macro(cx) { + if rustc_middle::lint::in_external_macro(cx.sess(), cx.tcx.hir().span_with_body(impl_item.hir_id())) + || is_executable_or_proc_macro(cx) + { return; } @@ -163,6 +167,6 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { } let attrs = cx.tcx.hir().attrs(impl_item.hir_id()); - check_missing_inline_attrs(cx, attrs, impl_item.span, desc); + check_missing_inline_attrs(cx, attrs, cx.tcx.hir().span_with_body(impl_item.hir_id()), desc); } } diff --git a/src/tools/clippy/clippy_lints/src/new_without_default.rs b/src/tools/clippy/clippy_lints/src/new_without_default.rs index de2899c3462a4..c004f29eaf37a 100644 --- a/src/tools/clippy/clippy_lints/src/new_without_default.rs +++ b/src/tools/clippy/clippy_lints/src/new_without_default.rs @@ -67,7 +67,7 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { for assoc_item in items { if let hir::AssocItemKind::Fn { has_self: false } = assoc_item.kind { let impl_item = cx.tcx.hir().impl_item(assoc_item.id); - if in_external_macro(cx.sess(), impl_item.span) { + if in_external_macro(cx.sess(), cx.tcx.hir().span_with_body(impl_item.hir_id())) { return; } if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind { @@ -129,7 +129,7 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { cx, NEW_WITHOUT_DEFAULT, id, - impl_item.span, + cx.tcx.hir().span_with_body(impl_item.hir_id()), &format!( "you should consider adding a `Default` implementation for `{}`", self_ty @@ -137,7 +137,7 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { |diag| { diag.suggest_prepend_item( cx, - item.span, + cx.tcx.hir().span_with_body(item.hir_id()), "try this", &create_new_without_default_suggest_msg(self_ty), Applicability::MaybeIncorrect, diff --git a/src/tools/clippy/clippy_lints/src/non_copy_const.rs b/src/tools/clippy/clippy_lints/src/non_copy_const.rs index 8aebce67917af..9bda9d8e0a5e4 100644 --- a/src/tools/clippy/clippy_lints/src/non_copy_const.rs +++ b/src/tools/clippy/clippy_lints/src/non_copy_const.rs @@ -237,7 +237,7 @@ impl<'tcx> LateLintPass<'tcx> for NonCopyConst { let ty = hir_ty_to_ty(cx.tcx, hir_ty); if is_unfrozen(cx, ty) && is_value_unfrozen_poly(cx, body_id, ty) { - lint(cx, Source::Item { item: it.span }); + lint(cx, Source::Item { item: cx.tcx.hir().span(it.hir_id()) }); } } } @@ -264,7 +264,7 @@ impl<'tcx> LateLintPass<'tcx> for NonCopyConst { // re-implementing the trait predicate evaluation specific to `Freeze`. && body_id_opt.map_or(true, |body_id| is_value_unfrozen_poly(cx, body_id, normalized)) { - lint(cx, Source::Assoc { item: trait_item.span }); + lint(cx, Source::Assoc { item: cx.tcx.hir().span(trait_item.hir_id()) }); } } } @@ -310,7 +310,7 @@ impl<'tcx> LateLintPass<'tcx> for NonCopyConst { lint( cx, Source::Assoc { - item: impl_item.span, + item: cx.tcx.hir().span(impl_item.hir_id()), }, ); } @@ -323,7 +323,7 @@ impl<'tcx> LateLintPass<'tcx> for NonCopyConst { let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty); if is_unfrozen(cx, ty) && is_value_unfrozen_poly(cx, *body_id, normalized) { - lint(cx, Source::Assoc { item: impl_item.span }); + lint(cx, Source::Assoc { item: cx.tcx.hir().span(impl_item.hir_id()) }); } }, _ => (), 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 b407f5bbed5f3..5d28618466e4f 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 @@ -201,7 +201,8 @@ impl_lint_pass!(PassByRefOrValue => [TRIVIALLY_COPY_PASS_BY_REF, LARGE_TYPES_PAS impl<'tcx> LateLintPass<'tcx> for PassByRefOrValue { fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) { - if item.span.from_expansion() { + let item_span = cx.tcx.hir().span(item.hir_id()); + if item_span.from_expansion() { return; } diff --git a/src/tools/clippy/clippy_lints/src/redundant_pub_crate.rs b/src/tools/clippy/clippy_lints/src/redundant_pub_crate.rs index c876bae2303ad..9ed2882d7a40e 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_pub_crate.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_pub_crate.rs @@ -44,7 +44,7 @@ impl<'tcx> LateLintPass<'tcx> for RedundantPubCrate { if let VisibilityKind::Crate { .. } = item.vis.node { if !cx.access_levels.is_exported(item.hir_id()) { if let Some(false) = self.is_exported.last() { - let span = item.span.with_hi(item.ident.span.hi()); + let span = cx.tcx.hir().span(item.hir_id()).with_hi(item.ident.span.hi()); let descr = cx.tcx.def_kind(item.def_id).descr(item.def_id.to_def_id()); span_lint_and_then( cx, diff --git a/src/tools/clippy/clippy_lints/src/types/mod.rs b/src/tools/clippy/clippy_lints/src/types/mod.rs index 4c8b133082e5a..cd63560b05893 100644 --- a/src/tools/clippy/clippy_lints/src/types/mod.rs +++ b/src/tools/clippy/clippy_lints/src/types/mod.rs @@ -1407,21 +1407,23 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitHasher { return; } + let item_span = cx.tcx.hir().span(item.hir_id()); + match item.kind { ItemKind::Impl(ref impl_) => { let mut vis = ImplicitHasherTypeVisitor::new(cx); vis.visit_ty(impl_.self_ty); for target in &vis.found { - if differing_macro_contexts(item.span, target.span()) { + if differing_macro_contexts(item_span, target.span()) { return; } let generics_suggestion_span = impl_.generics.span.substitute_dummy({ - let pos = snippet_opt(cx, item.span.until(target.span())) - .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4))); + let pos = snippet_opt(cx, item_span.until(target.span())) + .and_then(|snip| Some(item_span.lo() + BytePos(snip.find("impl")? as u32 + 4))); if let Some(pos) = pos { - Span::new(pos, pos, item.span.data().ctxt) + Span::new(pos, pos, item_span.data().ctxt) } else { return; } @@ -1458,13 +1460,13 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitHasher { continue; } let generics_suggestion_span = generics.span.substitute_dummy({ - let pos = snippet_opt(cx, item.span.until(cx.tcx.hir().span(body.params[0].pat.hir_id))) + 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)) + Some(item_span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32)) }) .expect("failed to create span for type parameters"); - Span::new(pos, pos, item.span.data().ctxt) + Span::new(pos, pos, item_span.data().ctxt) }); let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target); diff --git a/src/tools/clippy/clippy_lints/src/unused_self.rs b/src/tools/clippy/clippy_lints/src/unused_self.rs index bb705b7c78c3d..8b225ac097cd3 100644 --- a/src/tools/clippy/clippy_lints/src/unused_self.rs +++ b/src/tools/clippy/clippy_lints/src/unused_self.rs @@ -39,7 +39,7 @@ declare_lint_pass!(UnusedSelf => [UNUSED_SELF]); impl<'tcx> LateLintPass<'tcx> for UnusedSelf { fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &ImplItem<'_>) { - if impl_item.span.from_expansion() { + if cx.tcx.hir().span(impl_item.hir_id()).from_expansion() { return; } let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()); diff --git a/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs b/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs index 8cb7429849da6..3c15b52500d2f 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs @@ -60,7 +60,7 @@ impl<'tcx> LateLintPass<'tcx> for UnwrapInResult { if is_type_diagnostic_item(cx, return_ty(cx, impl_item.hir_id()), sym::result_type) || is_type_diagnostic_item(cx, return_ty(cx, impl_item.hir_id()), sym::option_type); then { - lint_impl_body(cx, impl_item.span, impl_item); + lint_impl_body(cx, impl_item); } } } @@ -108,9 +108,8 @@ impl<'a, 'tcx> Visitor<'tcx> for FindExpectUnwrap<'a, 'tcx> { } } -fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_item: &'tcx hir::ImplItem<'_>) { +fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) { if_chain! { - if let ImplItemKind::Fn(_, body_id) = impl_item.kind; then { let body = cx.tcx.hir().body(body_id); @@ -123,6 +122,7 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_item: &'tc // if we've found one, lint if !fpu.result.is_empty() { + let impl_span = cx.tcx.hir().span_with_body(impl_item.hir_id()); span_lint_and_then( cx, UNWRAP_IN_RESULT, diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index f0523cec6211d..8362313644fcf 100644 --- a/src/tools/clippy/clippy_lints/src/use_self.rs +++ b/src/tools/clippy/clippy_lints/src/use_self.rs @@ -287,7 +287,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { } } - if in_macro(expr.span) | !meets_msrv(self.msrv.as_ref(), &USE_SELF_MSRV) { + if in_macro(cx.tcx.hir().span(expr.hir_id)) | !meets_msrv(self.msrv.as_ref(), &USE_SELF_MSRV) { return; } diff --git a/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs b/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs index 0a347516c3ad2..38b87db135358 100644 --- a/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs +++ b/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs @@ -342,6 +342,7 @@ impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass { return; } + let item_span = cx.tcx.hir().span(item.hir_id); if let hir::ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind { if is_lint_ref_type(cx, ty) { let expr = &cx.tcx.hir().body(body_id).value; @@ -362,15 +363,15 @@ impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass { span_lint( cx, DEFAULT_LINT, - item.span, + item_span, &format!("the lint `{}` has the default lint description", item.ident.name), ); } } - self.declared_lints.insert(item.ident.name, item.span); + self.declared_lints.insert(item.ident.name, item_span); } - } else if is_expn_of(item.span, "impl_lint_pass").is_some() - || is_expn_of(item.span, "declare_lint_pass").is_some() + } else if is_expn_of(item_span, "impl_lint_pass").is_some() + || is_expn_of(item_span, "declare_lint_pass").is_some() { if let hir::ItemKind::Impl(hir::Impl { of_trait: None, @@ -878,7 +879,8 @@ impl<'tcx> LateLintPass<'tcx> for InvalidPaths { }).collect(); if !check_path(cx, &path[..]); then { - span_lint(cx, CLIPPY_LINTS_INTERNAL, item.span, "invalid path"); + let item_span = cx.tcx.hir().span(item.hir_id); + span_lint(cx, CLIPPY_LINTS_INTERNAL, item_span, "invalid path"); } } } diff --git a/src/tools/clippy/clippy_lints/src/wildcard_imports.rs b/src/tools/clippy/clippy_lints/src/wildcard_imports.rs index 094b1a42346c2..5c2a9546b14a9 100644 --- a/src/tools/clippy/clippy_lints/src/wildcard_imports.rs +++ b/src/tools/clippy/clippy_lints/src/wildcard_imports.rs @@ -112,7 +112,7 @@ impl LateLintPass<'_> for WildcardImports { } if_chain! { if let ItemKind::Use(use_path, UseKind::Glob) = &item.kind; - if self.warn_on_all || !self.check_exceptions(item, use_path.segments); + if self.warn_on_all || !self.check_exceptions(cx, item, use_path.segments); let used_imports = cx.tcx.names_imported_by_glob_use(item.def_id); if !used_imports.is_empty(); // Already handled by `unused_imports` then { @@ -132,9 +132,10 @@ impl LateLintPass<'_> for WildcardImports { // formattings like `use _ :: *;`, we extend it up to, but not including the // `;`. In nested imports, like `use _::{inner::*, _}` there is no `;` and we // can just use the end of the item span - let mut span = use_path.span.with_hi(item.span.hi()); + let item_span = cx.tcx.hir().span(item.hir_id()); + let mut span = use_path.span.with_hi(item_span.hi()); if snippet(cx, span, "").ends_with(';') { - span = use_path.span.with_hi(item.span.hi() - BytePos(1)); + span = use_path.span.with_hi(item_span.hi() - BytePos(1)); } ( span, false, @@ -189,8 +190,9 @@ impl LateLintPass<'_> for WildcardImports { } impl WildcardImports { - fn check_exceptions(&self, item: &Item<'_>, segments: &[PathSegment<'_>]) -> bool { - in_macro(item.span) + fn check_exceptions(&self, cx: &LateContext<'_>, item: &Item<'_>, segments: &[PathSegment<'_>]) -> bool { + let item_span = cx.tcx.hir().span(item.hir_id()); + in_macro(item_span) || is_prelude_import(segments) || (is_super_only_import(segments) && self.test_modules_deep > 0) } From d632f42dfccfdba2a69e09166296c0d0726b9ea4 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Fri, 11 Dec 2020 23:44:08 +0100 Subject: [PATCH 37/41] Remove span from hir::ForeignItem. --- compiler/rustc_ast_lowering/src/item.rs | 1 - compiler/rustc_hir/src/hir.rs | 3 +-- compiler/rustc_hir/src/stable_hash_impls.rs | 3 +-- compiler/rustc_lint/src/builtin.rs | 12 +++++++----- compiler/rustc_passes/src/dead.rs | 7 ++++++- compiler/rustc_passes/src/weak_lang_items.rs | 2 +- compiler/rustc_typeck/src/check/check.rs | 7 ++++++- compiler/rustc_typeck/src/check/intrinsic.rs | 19 ++++++++++++------- src/librustdoc/doctest.rs | 3 ++- 9 files changed, 36 insertions(+), 21 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 4710006bfd1ce..f88be91718fb8 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -728,7 +728,6 @@ impl<'hir> LoweringContext<'_, 'hir> { ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"), }, vis: self.lower_visibility(&i.vis, None), - span: i.span, } } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 480ab5bc7e9c1..49a53211a5cfa 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2880,7 +2880,6 @@ pub struct ForeignItem<'hir> { pub ident: Ident, pub kind: ForeignItemKind<'hir>, pub def_id: LocalDefId, - pub span: Span, pub vis: Visibility<'hir>, } @@ -3044,5 +3043,5 @@ mod size_asserts { rustc_data_structures::static_assert_size!(super::Item<'static>, 176); rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 120); rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 144); - rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136); + rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 128); } diff --git a/compiler/rustc_hir/src/stable_hash_impls.rs b/compiler/rustc_hir/src/stable_hash_impls.rs index ea9ab7fede823..60c40584090af 100644 --- a/compiler/rustc_hir/src/stable_hash_impls.rs +++ b/compiler/rustc_hir/src/stable_hash_impls.rs @@ -165,12 +165,11 @@ impl HashStable for ImplItem<'_> { impl HashStable for ForeignItem<'_> { fn hash_stable(&self, hcx: &mut HirCtx, hasher: &mut StableHasher) { - let ForeignItem { def_id: _, ident, ref kind, span, ref vis } = *self; + let ForeignItem { def_id: _, ident, ref kind, ref vis } = *self; hcx.hash_hir_item_like(|hcx| { ident.name.hash_stable(hcx, hasher); kind.hash_stable(hcx, hasher); - span.hash_stable(hcx, hasher); vis.hash_stable(hcx, hasher); }); } diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index b1119c28bb665..49ede4f25f61c 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2927,11 +2927,13 @@ impl<'tcx> LateLintPass<'tcx> for ClashingExternDeclarations { // We want to ensure that we use spans for both decls that include where the // name was defined, whether that was from the link_name attribute or not. - let get_relevant_span = - |fi: &hir::ForeignItem<'_>| match Self::name_of_extern_decl(tcx, fi) { - SymbolName::Normal(_) => fi.span, - SymbolName::Link(_, annot_span) => fi.span.to(annot_span), - }; + let get_relevant_span = |fi: &hir::ForeignItem<'_>| { + let fi_span = tcx.hir().span(fi.hir_id()); + match Self::name_of_extern_decl(tcx, fi) { + SymbolName::Normal(_) => fi_span, + SymbolName::Link(_, annot_span) => fi_span.to(annot_span), + } + }; // Finally, emit the diagnostic. tcx.struct_span_lint_hir( CLASHING_EXTERN_DECLARATIONS, diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 316b58e914a54..eda0476bee90f 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -646,7 +646,12 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> { fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem<'tcx>) { if self.should_warn_about_foreign_item(fi) { - self.warn_dead_code(fi.hir_id(), fi.span, fi.ident.name, "used"); + self.warn_dead_code( + fi.hir_id(), + self.tcx.hir().span(fi.hir_id()), + fi.ident.name, + "used", + ); } intravisit::walk_foreign_item(self, fi); } diff --git a/compiler/rustc_passes/src/weak_lang_items.rs b/compiler/rustc_passes/src/weak_lang_items.rs index de369ba9bbbe2..ef73806c8d661 100644 --- a/compiler/rustc_passes/src/weak_lang_items.rs +++ b/compiler/rustc_passes/src/weak_lang_items.rs @@ -99,7 +99,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { let check_name = |attr, sym| self.tcx.sess.check_name(attr, sym); let attrs = self.tcx.hir().attrs(i.hir_id()); if let Some((lang_item, _)) = lang_items::extract(check_name, attrs) { - self.register(lang_item, i.span); + self.register(lang_item, self.tcx.hir().span(i.hir_id())); } intravisit::walk_foreign_item(self, i) } diff --git a/compiler/rustc_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index f29d6cfd04463..1e9aba87e94cc 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -835,7 +835,12 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { let item = tcx.hir().foreign_item(item.id); match item.kind { hir::ForeignItemKind::Fn(ref fn_decl, _, _) => { - require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span); + require_c_abi_if_c_variadic( + tcx, + fn_decl, + abi, + tcx.hir().span(item.hir_id()), + ); } hir::ForeignItemKind::Static(..) => { check_static_inhabited(tcx, item.def_id); diff --git a/compiler/rustc_typeck/src/check/intrinsic.rs b/compiler/rustc_typeck/src/check/intrinsic.rs index dedf96863eaf6..3cca92aeb31f5 100644 --- a/compiler/rustc_typeck/src/check/intrinsic.rs +++ b/compiler/rustc_typeck/src/check/intrinsic.rs @@ -23,11 +23,12 @@ fn equate_intrinsic_type<'tcx>( n_tps: usize, sig: ty::PolyFnSig<'tcx>, ) { + let it_span = tcx.hir().span(it.hir_id()); match it.kind { hir::ForeignItemKind::Fn(..) => {} _ => { - struct_span_err!(tcx.sess, it.span, E0622, "intrinsic must be a function") - .span_label(it.span, "expected a function") + struct_span_err!(tcx.sess, it_span, E0622, "intrinsic must be a function") + .span_label(it_span, "expected a function") .emit(); return; } @@ -49,7 +50,7 @@ fn equate_intrinsic_type<'tcx>( } let fty = tcx.mk_fn_ptr(sig); - let cause = ObligationCause::new(it.span, it.hir_id(), ObligationCauseCode::IntrinsicType); + let cause = ObligationCause::new(it_span, it.hir_id(), ObligationCauseCode::IntrinsicType); require_same_types(tcx, &cause, tcx.mk_fn_ptr(tcx.fn_sig(it.def_id)), fty); } @@ -130,7 +131,8 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { | "umin" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], param(0)), "fence" | "singlethreadfence" => (0, Vec::new(), tcx.mk_unit()), op => { - tcx.sess.emit_err(UnrecognizedAtomicOperation { span: it.span, op }); + let it_span = tcx.hir().span(it.hir_id()); + tcx.sess.emit_err(UnrecognizedAtomicOperation { span: it_span, op }); return; } }; @@ -359,7 +361,8 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { sym::nontemporal_store => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], tcx.mk_unit()), other => { - tcx.sess.emit_err(UnrecognizedIntrinsicFunction { span: it.span, name: other }); + let it_span = tcx.hir().span(it.hir_id()); + tcx.sess.emit_err(UnrecognizedIntrinsicFunction { span: it_span, name: other }); return; } }; @@ -440,14 +443,16 @@ pub fn check_platform_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) (2, params, param(1)) } Err(_) => { - tcx.sess.emit_err(SimdShuffleMissingLength { span: it.span, name }); + let it_span = tcx.hir().span(it.hir_id()); + tcx.sess.emit_err(SimdShuffleMissingLength { span: it_span, name }); return; } } } _ => { let msg = format!("unrecognized platform-specific intrinsic function: `{}`", name); - tcx.sess.struct_span_err(it.span, &msg).emit(); + let it_span = tcx.hir().span(it.hir_id()); + tcx.sess.struct_span_err(it_span, &msg).emit(); return; } }; diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 7541eaa2f8aee..1edce3edbf103 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -1075,7 +1075,8 @@ impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> } fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem<'_>) { - self.visit_testable(item.ident.to_string(), item.hir_id(), item.span, |this| { + let item_span = self.tcx.hir().span(item.hir_id()); + self.visit_testable(item.ident.to_string(), item.hir_id(), item_span, |this| { intravisit::walk_foreign_item(this, item); }); } From 0d9d1e08e191e895c8a14ea65e043046f8270950 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Fri, 8 May 2020 12:15:40 +0200 Subject: [PATCH 38/41] Remove Span from hir::Ty. --- compiler/rustc_ast_lowering/src/expr.rs | 2 +- compiler/rustc_ast_lowering/src/lib.rs | 6 +- compiler/rustc_ast_lowering/src/path.rs | 2 +- compiler/rustc_hir/src/hir.rs | 11 ++-- compiler/rustc_hir_pretty/src/lib.rs | 6 +- .../src/infer/error_reporting/mod.rs | 2 +- .../infer/error_reporting/need_type_info.rs | 8 ++- .../nice_region_error/different_lifetimes.rs | 13 +++-- .../nice_region_error/named_anon_conflict.rs | 4 +- .../nice_region_error/static_impl_trait.rs | 7 ++- .../error_reporting/nice_region_error/util.rs | 2 +- compiler/rustc_lint/src/internal.rs | 8 ++- compiler/rustc_lint/src/types.rs | 9 ++- compiler/rustc_middle/src/ich/impls_hir.rs | 3 +- compiler/rustc_middle/src/ty/context.rs | 2 +- compiler/rustc_middle/src/ty/util.rs | 2 +- .../diagnostics/conflict_errors.rs | 8 +-- .../diagnostics/mutability_errors.rs | 10 ++-- .../borrow_check/diagnostics/region_name.rs | 15 +++-- compiler/rustc_mir_build/src/build/mod.rs | 8 +-- compiler/rustc_mir_build/src/thir/cx/block.rs | 2 +- compiler/rustc_privacy/src/lib.rs | 2 +- compiler/rustc_resolve/src/late/lifetimes.rs | 12 ++-- .../src/traits/error_reporting/mod.rs | 7 ++- .../src/traits/error_reporting/suggestions.rs | 25 ++++++--- .../src/traits/object_safety.rs | 10 ++-- .../rustc_trait_selection/src/traits/wf.rs | 13 +++-- compiler/rustc_typeck/src/astconv/errors.rs | 12 +++- compiler/rustc_typeck/src/astconv/mod.rs | 29 ++++++---- compiler/rustc_typeck/src/check/_match.rs | 2 +- compiler/rustc_typeck/src/check/check.rs | 39 +++++++++---- compiler/rustc_typeck/src/check/closure.rs | 13 +++-- compiler/rustc_typeck/src/check/coercion.rs | 2 +- .../rustc_typeck/src/check/compare_method.rs | 42 ++++++++------ compiler/rustc_typeck/src/check/demand.rs | 3 +- compiler/rustc_typeck/src/check/expr.rs | 5 +- .../rustc_typeck/src/check/fn_ctxt/_impl.rs | 3 +- .../rustc_typeck/src/check/fn_ctxt/checks.rs | 9 +-- .../src/check/fn_ctxt/suggestions.rs | 2 +- .../rustc_typeck/src/check/gather_locals.rs | 3 +- .../rustc_typeck/src/check/method/suggest.rs | 5 +- compiler/rustc_typeck/src/check/mod.rs | 3 +- compiler/rustc_typeck/src/check/wfcheck.rs | 56 ++++++++++++------- compiler/rustc_typeck/src/check/writeback.rs | 3 +- .../rustc_typeck/src/coherence/builtin.rs | 9 ++- .../src/coherence/inherent_impls.rs | 5 +- compiler/rustc_typeck/src/coherence/orphan.rs | 3 +- compiler/rustc_typeck/src/collect.rs | 26 +++++---- compiler/rustc_typeck/src/collect/type_of.rs | 9 ++- src/librustdoc/clean/mod.rs | 3 +- .../clippy_lints/src/cognitive_complexity.rs | 2 +- .../clippy/clippy_lints/src/from_over_into.rs | 2 +- .../clippy/clippy_lints/src/functions.rs | 26 +++++---- .../clippy_lints/src/future_not_send.rs | 2 +- .../clippy_lints/src/large_enum_variant.rs | 4 +- .../clippy/clippy_lints/src/lifetimes.rs | 2 +- .../clippy/clippy_lints/src/macro_use.rs | 5 +- .../clippy_lints/src/manual_async_fn.rs | 4 +- .../clippy/clippy_lints/src/methods/mod.rs | 2 +- src/tools/clippy/clippy_lints/src/misc.rs | 5 +- src/tools/clippy/clippy_lints/src/mut_key.rs | 8 ++- src/tools/clippy/clippy_lints/src/mut_mut.rs | 2 +- .../src/needless_pass_by_value.rs | 12 ++-- .../clippy_lints/src/pass_by_ref_or_value.rs | 13 +++-- src/tools/clippy/clippy_lints/src/ptr.rs | 33 ++++++----- .../clippy/clippy_lints/src/ref_option_ref.rs | 6 +- .../clippy/clippy_lints/src/trait_bounds.rs | 2 +- .../clippy_lints/src/transmute/utils.rs | 2 +- .../clippy_lints/src/types/borrowed_box.rs | 4 +- .../clippy/clippy_lints/src/types/box_vec.rs | 2 +- .../clippy_lints/src/types/linked_list.rs | 2 +- .../clippy/clippy_lints/src/types/mod.rs | 17 +++--- .../clippy_lints/src/types/option_option.rs | 2 +- .../clippy_lints/src/types/rc_buffer.rs | 12 ++-- .../src/types/redundant_allocation.rs | 12 ++-- .../clippy/clippy_lints/src/types/utils.rs | 4 +- .../clippy/clippy_lints/src/types/vec_box.rs | 6 +- .../clippy_lints/src/unnecessary_wraps.rs | 4 +- src/tools/clippy/clippy_lints/src/use_self.rs | 9 ++- .../clippy_lints/src/vec_init_then_push.rs | 2 +- .../clippy_lints/src/zero_sized_map_values.rs | 5 +- 81 files changed, 419 insertions(+), 279 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 3d3ab7540a84c..c4bff914a0b97 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -655,7 +655,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(span), kind: hir::TyKind::Infer, span }; + let input_ty = hir::Ty { hir_id: self.next_id(span), kind: hir::TyKind::Infer }; // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`. let decl = self.arena.alloc(hir::FnDecl { diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 43287658a931f..250379672fafb 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1346,7 +1346,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(span), kind, span } + hir::Ty { hir_id: self.next_id(span), kind } } fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> { @@ -1543,7 +1543,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } }; - hir::Ty { kind, span: t.span, hir_id: self.lower_node_id(t.id, t.span) } + hir::Ty { kind, hir_id: self.lower_node_id(t.id, t.span) } } fn lower_opaque_impl_trait( @@ -2706,7 +2706,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { _ => hir::TyKind::Path(qpath), }; - hir::Ty { hir_id, kind, span } + hir::Ty { hir_id, kind } } /// Invoked to create the lifetime argument for a type `&T` diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index 7104927d52fbe..641af83407f81 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -409,7 +409,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { FnRetTy::Default(_) => this.arena.alloc(this.ty_tup(*span, &[])), }; let args = smallvec![GenericArg::Type(this.ty_tup(*inputs_span, inputs))]; - let binding = this.output_ty_binding(output_ty.span, output_ty); + let binding = this.output_ty_binding(this.spans[output_ty.hir_id], output_ty); ( GenericArgsCtor { args, bindings: arena_vec![this; binding], parenthesized: true }, false, diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 49a53211a5cfa..979789a88f82a 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1793,10 +1793,10 @@ impl<'hir> QPath<'hir> { /// Returns the span of the qself of this `QPath`. For example, `()` in /// `<() as Trait>::method`. - pub fn qself_span(&self) -> Span { + pub fn qself_span(&self, get_span: impl Fn(HirId) -> Span) -> Span { match *self { QPath::Resolved(_, path) => path.span, - QPath::TypeRelative(qself, _) => qself.span, + QPath::TypeRelative(qself, _) => get_span(qself.hir_id), QPath::LangItem(_, span) => span, } } @@ -2151,7 +2151,6 @@ impl TypeBinding<'_> { pub struct Ty<'hir> { pub hir_id: HirId, pub kind: TyKind<'hir>, - pub span: Span, } /// Not represented directly in the AST; referred to by name through a `ty_path`. @@ -2476,10 +2475,10 @@ pub enum FnRetTy<'hir> { } impl FnRetTy<'_> { - pub fn span(&self) -> Span { + pub fn span(&self, get_span: impl Fn(HirId) -> Span) -> Span { match *self { Self::DefaultReturn(span) => span, - Self::Return(ref ty) => ty.span, + Self::Return(ref ty) => get_span(ty.hir_id), } } } @@ -3038,7 +3037,7 @@ mod size_asserts { rustc_data_structures::static_assert_size!(super::Expr<'static>, 64); rustc_data_structures::static_assert_size!(super::Pat<'static>, 80); rustc_data_structures::static_assert_size!(super::QPath<'static>, 24); - rustc_data_structures::static_assert_size!(super::Ty<'static>, 72); + rustc_data_structures::static_assert_size!(super::Ty<'static>, 64); rustc_data_structures::static_assert_size!(super::Item<'static>, 176); rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 120); diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index e0c3efe0caf3f..b70a34d5b42b9 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -381,7 +381,7 @@ impl<'a> State<'a> { } pub fn print_type(&mut self, ty: &hir::Ty<'_>) { - self.maybe_print_comment(ty.span.lo()); + self.maybe_print_comment(self.span(ty.hir_id).lo()); self.ibox(0); match ty.kind { hir::TyKind::Slice(ref ty) => { @@ -2205,7 +2205,7 @@ impl<'a> State<'a> { match decl.output { hir::FnRetTy::Return(ref ty) => { self.print_type(&ty); - self.maybe_print_comment(ty.span.lo()) + self.maybe_print_comment(self.span(ty.hir_id).lo()) } hir::FnRetTy::DefaultReturn(..) => unreachable!(), } @@ -2397,7 +2397,7 @@ impl<'a> State<'a> { self.end(); if let hir::FnRetTy::Return(ref output) = decl.output { - self.maybe_print_comment(output.span.lo()) + self.maybe_print_comment(self.span(output.hir_id).lo()) } } diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 7396a2b518307..077bee1bddbda 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -181,7 +181,7 @@ fn msg_span_from_early_bound_and_free_regions( ty::ReFree(ref fr) => match fr.bound_region { ty::BrAnon(idx) => { if let Some((ty, _)) = find_anon_type(tcx, region, &fr.bound_region) { - ("the anonymous lifetime defined on".to_string(), ty.span) + ("the anonymous lifetime defined on".to_string(), tcx.hir().span(ty.hir_id)) } else { ( format!("the anonymous lifetime #{} defined on", idx + 1), 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 cbeefc8d7f88c..ec297fec01b57 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 @@ -214,6 +214,7 @@ impl UseDiagnostic<'_> { /// Suggest giving an appropriate return type to a closure expression. fn closure_return_type_suggestion( + tcx: TyCtxt<'_>, err: &mut DiagnosticBuilder<'_>, output: &FnRetTy<'_>, body: &Body<'_>, @@ -224,9 +225,11 @@ fn closure_return_type_suggestion( _ => ("", ""), }; let suggestion = match body.value.kind { - ExprKind::Block(..) => vec![(output.span(), format!("{}{}{}", arrow, ret, post))], + ExprKind::Block(..) => { + vec![(output.span(|id| tcx.hir().span(id)), format!("{}{}{}", arrow, ret, post))] + } _ => vec![ - (output.span(), format!("{}{}{}{{ ", arrow, ret, post)), + (output.span(|id| tcx.hir().span(id)), format!("{}{}{}{{ ", arrow, ret, post)), (body.value.span.shrink_to_hi(), " }".to_string()), ], }; @@ -554,6 +557,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { if let Some((decl, body_id)) = closure_decl_and_body_id { closure_return_type_suggestion( + self.tcx, &mut err, &decl.output, self.tcx.hir().body(body_id), diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs index 1b35c4032f44c..e5c2e820658e4 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs @@ -103,6 +103,8 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { None => String::new(), }; + let ty_sub_span = self.tcx().hir().span(ty_sub.hir_id); + let ty_sup_span = self.tcx().hir().span(ty_sup.hir_id); let (span_1, span_2, main_label, span_label, future_return_type) = match (sup_is_ret_type, sub_is_ret_type) { (None, None) => { @@ -117,7 +119,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { format!("...but data{} flows{} here", span_label_var1, span_label_var2), ) }; - (ty_sup.span, ty_sub.span, main_label_1, span_label_1, None) + (ty_sup_span, ty_sub_span, main_label_1, span_label_1, None) } (Some(ret_span), _) => { @@ -129,7 +131,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { }; ( - ty_sub.span, + ty_sub_span, ret_span, format!( "this parameter and the {} are declared with different lifetimes...", @@ -148,7 +150,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { }; ( - ty_sup.span, + ty_sup_span, ret_span, format!( "this parameter and the {} are declared with different lifetimes...", @@ -167,11 +169,12 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { e.span_label(span, span_label); if let Some(t) = future_return_type { + let t_span = self.tcx().hir().span(t.hir_id); let snip = self .tcx() .sess .source_map() - .span_to_snippet(t.span) + .span_to_snippet(t_span) .ok() .and_then(|s| match (&t.kind, s.as_str()) { (rustc_hir::TyKind::Tup(&[]), "") => Some("()".to_string()), @@ -181,7 +184,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { .unwrap_or("{unnamed_type}".to_string()); e.span_label( - t.span, + t_span, &format!("this `async fn` implicitly returns an `impl Future`", snip), ); } diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/named_anon_conflict.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/named_anon_conflict.rs index 2f3c0d6957a61..852f43b86db40 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/named_anon_conflict.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/named_anon_conflict.rs @@ -86,7 +86,9 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { debug!("try_report_named_anon_conflict: ret ty {:?}", ty); if sub == &ty::ReStatic - && v.0.into_iter().any(|t| t.span.desugaring_kind().is_none()) + && v.0 + .into_iter() + .any(|t| self.tcx().hir().span(t.hir_id).desugaring_kind().is_none()) { // If the failure is due to a `'static` requirement coming from a `dyn` or // `impl` Trait that *isn't* caused by `async fn` desugaring, handle this case diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs index fa0d5b8301349..fdad0ba008957 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs @@ -225,7 +225,8 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { let add_static_bound = "alternatively, add an explicit `'static` bound to this reference"; let plus_lt = format!(" + {}", lifetime_name); for fn_return in fn_returns { - if fn_return.span.desugaring_kind().is_some() { + let fn_return_span = self.tcx().hir().span(fn_return.hir_id); + if fn_return_span.desugaring_kind().is_some() { // Skip `async` desugaring `impl Future`. continue; } @@ -280,7 +281,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { { } else { err.span_suggestion_verbose( - fn_return.span.shrink_to_hi(), + fn_return_span.shrink_to_hi(), &format!( "{declare} `impl Trait` {captures}, {explicit}", declare = declare, @@ -295,7 +296,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { TyKind::TraitObject(_, lt) => match lt.name { LifetimeName::ImplicitObjectLifetimeDefault => { err.span_suggestion_verbose( - fn_return.span.shrink_to_hi(), + fn_return_span.shrink_to_hi(), &format!( "{declare} trait object {captures}, {explicit}", declare = declare, diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs index 17a56046a5cc8..58ce679a97b62 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs @@ -154,7 +154,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { let late_bound_regions = self.tcx().collect_referenced_late_bound_regions(&sig.output()); if late_bound_regions.iter().any(|r| *r == br) { - return Some(decl.output.span()); + return Some(decl.output.span(|id| self.tcx().hir().span(id))); } } None diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 9b1a339572ec3..238af96508192 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -119,7 +119,8 @@ impl<'tcx> LateLintPass<'tcx> for TyTyKind { .emit(); }) } else { - if ty.span.from_expansion() { + let ty_span = cx.tcx.hir().span(ty.hir_id); + if ty_span.from_expansion() { return; } if let Some(t) = is_ty_or_ty_ctxt(cx, ty) { @@ -148,10 +149,11 @@ impl<'tcx> LateLintPass<'tcx> for TyTyKind { } } if let Some(t) = is_ty_or_ty_ctxt(cx, &inner_ty) { - cx.struct_span_lint(TY_PASS_BY_REFERENCE, ty.span, |lint| { + let ty_span = cx.tcx.hir().span(ty.hir_id); + cx.struct_span_lint(TY_PASS_BY_REFERENCE, ty_span, |lint| { lint.build(&format!("passing `{}` by reference", t)) .span_suggestion( - ty.span, + ty_span, "try passing by value", t, // Changing type of function argument diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 8405ac3f725a3..1a06d95dd8505 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1258,12 +1258,14 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { let sig = self.cx.tcx.erase_late_bound_regions(sig); for (input_ty, input_hir) in sig.inputs().iter().zip(decl.inputs) { - self.check_type_for_ffi_and_report_errors(input_hir.span, input_ty, false, false); + let input_span = self.cx.tcx.hir().span(input_hir.hir_id); + self.check_type_for_ffi_and_report_errors(input_span, input_ty, false, false); } if let hir::FnRetTy::Return(ref ret_hir) = decl.output { let ret_ty = sig.output(); - self.check_type_for_ffi_and_report_errors(ret_hir.span, ret_ty, false, true); + let ret_span = self.cx.tcx.hir().span(ret_hir.hir_id); + self.check_type_for_ffi_and_report_errors(ret_span, ret_ty, false, true); } } @@ -1292,7 +1294,8 @@ impl<'tcx> LateLintPass<'tcx> for ImproperCTypesDeclarations { vis.check_foreign_fn(it.hir_id(), decl); } hir::ForeignItemKind::Static(ref ty, _) => { - vis.check_foreign_static(it.hir_id(), ty.span); + let ty_span = cx.tcx.hir().span(ty.hir_id); + vis.check_foreign_static(it.hir_id(), ty_span); } hir::ForeignItemKind::Type => (), } diff --git a/compiler/rustc_middle/src/ich/impls_hir.rs b/compiler/rustc_middle/src/ich/impls_hir.rs index abf56832329b2..44c03af4f66fa 100644 --- a/compiler/rustc_middle/src/ich/impls_hir.rs +++ b/compiler/rustc_middle/src/ich/impls_hir.rs @@ -75,10 +75,9 @@ impl<'ctx> rustc_hir::HashStableContext for StableHashingContext<'ctx> { fn hash_hir_ty(&mut self, ty: &hir::Ty<'_>, hasher: &mut StableHasher) { self.while_hashing_hir_bodies(true, |hcx| { - let hir::Ty { hir_id: _, ref kind, ref span } = *ty; + let hir::Ty { hir_id: _, ref kind } = *ty; kind.hash_stable(hcx, hasher); - span.hash_stable(hcx, hasher); }) } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index e1d79248171a8..13c73abdf97aa 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1500,7 +1500,7 @@ impl<'tcx> TyCtxt<'tcx> { let output = self.erase_late_bound_regions(sig.output()); if output.is_impl_trait() { let fn_decl = self.hir().fn_decl_by_hir_id(hir_id).unwrap(); - Some((output, fn_decl.output.span())) + Some((output, fn_decl.output.span(|id| self.hir().span(id)))) } else { None } diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index bdcf66b3d0c27..a054b8a0136c5 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -876,7 +876,7 @@ impl<'tcx> ty::TyS<'tcx> { .map(|id| tcx.hir().local_def_id_to_hir_id(id)) .and_then(|id| tcx.hir().find(id)) { - Some(hir::Node::Field(field)) => field.ty.span, + Some(hir::Node::Field(field)) => tcx.hir().span(field.ty.hir_id), _ => sp, }; match is_type_structurally_recursive( diff --git a/compiler/rustc_mir/src/borrow_check/diagnostics/conflict_errors.rs b/compiler/rustc_mir/src/borrow_check/diagnostics/conflict_errors.rs index eb942b195b252..eb2c1c0131976 100644 --- a/compiler/rustc_mir/src/borrow_check/diagnostics/conflict_errors.rs +++ b/compiler/rustc_mir/src/borrow_check/diagnostics/conflict_errors.rs @@ -2024,7 +2024,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // We use a mix of the HIR and the Ty types to get information // as the HIR doesn't have full types for closure arguments. let return_ty = sig.output().skip_binder(); - let mut return_span = fn_decl.output.span(); + let mut return_span = fn_decl.output.span(|id| self.infcx.tcx.hir().span(id)); if let hir::FnRetTy::Return(ty) = &fn_decl.output { if let hir::TyKind::Rptr(lifetime, _) = ty.kind { return_span = lifetime.span; @@ -2041,7 +2041,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // This is case 2 from above but only for closures, return type is anonymous // reference so we select // the first argument. - let argument_span = fn_decl.inputs.first()?.span; + let argument_span = self.infcx.tcx.hir().span(fn_decl.inputs.first()?.hir_id); let argument_ty = sig.inputs().skip_binder().first()?; // Closure arguments are wrapped in a tuple, so we need to get the first @@ -2061,10 +2061,10 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { ty::Ref(_, _, _) => { // This is also case 2 from above but for functions, return type is still an // anonymous reference so we select the first argument. - let argument_span = fn_decl.inputs.first()?.span; + let argument_span = self.infcx.tcx.hir().span(fn_decl.inputs.first()?.hir_id); let argument_ty = sig.inputs().skip_binder().first()?; - let return_span = fn_decl.output.span(); + let return_span = fn_decl.output.span(|id| self.infcx.tcx.hir().span(id)); let return_ty = sig.output().skip_binder(); // We expect the first argument to be a reference. diff --git a/compiler/rustc_mir/src/borrow_check/diagnostics/mutability_errors.rs b/compiler/rustc_mir/src/borrow_check/diagnostics/mutability_errors.rs index 2f40a90fb5516..e67e3ae6e2800 100644 --- a/compiler/rustc_mir/src/borrow_check/diagnostics/mutability_errors.rs +++ b/compiler/rustc_mir/src/borrow_check/diagnostics/mutability_errors.rs @@ -676,7 +676,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { }, ) }) - .map(|arg| arg.span) + .map(|arg| hir.span(arg.hir_id)) .unwrap_or(ident.span), ), _ => None, @@ -709,7 +709,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { }) => { err.span_label(ident.span, ""); err.span_label( - sig.decl.output.span(), + sig.decl.output.span(|id| hir.span(id)), "change this to return `FnMut` instead of `Fn`", ); err.span_label(self.body.span, "in this closure"); @@ -870,15 +870,17 @@ fn annotate_struct_field( // Get the snippets in two parts - the named lifetime (if there is one) and // type being referenced, that way we can reconstruct the snippet without loss // of detail. - let type_snippet = tcx.sess.source_map().span_to_snippet(ty.span).ok()?; + let ty_span = tcx.hir().span(ty.hir_id); + let type_snippet = tcx.sess.source_map().span_to_snippet(ty_span).ok()?; let lifetime_snippet = if !lifetime.is_elided() { format!("{} ", tcx.sess.source_map().span_to_snippet(lifetime.span).ok()?) } else { String::new() }; + let field_ty_span = tcx.hir().span(field.ty.hir_id); return Some(( - field.ty.span, + field_ty_span, format!("&{}mut {}", lifetime_snippet, &*type_snippet,), )); } 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 a3426d0f69a81..eb74c4bc14c08 100644 --- a/compiler/rustc_mir/src/borrow_check/diagnostics/region_name.rs +++ b/compiler/rustc_mir/src/borrow_check/diagnostics/region_name.rs @@ -497,7 +497,8 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { if region.to_region_vid() == needle_fr { // Just grab the first character, the `&`. let source_map = self.infcx.tcx.sess.source_map(); - let ampersand_span = source_map.start_point(hir_ty.span); + let hir_ty_span = self.infcx.tcx.hir().span(hir_ty.hir_id); + let ampersand_span = source_map.start_point(hir_ty_span); return Some(RegionNameHighlight::MatchedHirTy(ampersand_span)); } @@ -695,7 +696,9 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { hir::FnRetTy::DefaultReturn(_) => { (tcx.sess.source_map().end_point(*span), None) } - hir::FnRetTy::Return(hir_ty) => (return_ty.output.span(), Some(hir_ty)), + hir::FnRetTy::Return(hir_ty) => { + (return_ty.output.span(|id| tcx.hir().span(id)), Some(hir_ty)) + } }; let mir_description = match hir.body(*body_id).generator_kind { Some(hir::GeneratorKind::Async(gen)) => match gen { @@ -707,7 +710,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { .fn_decl() .expect("generator lowered from async fn should be in fn") .output; - span = output.span(); + span = output.span(|id| tcx.hir().span(id)); if let hir::FnRetTy::Return(ret) = output { hir_ty = Some(self.get_future_inner_return_ty(*ret)); } @@ -725,7 +728,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { hir::FnRetTy::DefaultReturn(_) => None, hir::FnRetTy::Return(ty) => Some(ty), }; - (fn_decl.output.span(), "", hir_ty) + (fn_decl.output.span(|id| tcx.hir().span(id)), "", hir_ty) } None => (self.body.span, "", None), }, @@ -787,14 +790,14 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { ty } else { span_bug!( - hir_ty.span, + hir.span(hir_ty.hir_id), "bounds from lowered return type of async fn did not match expected format: {:?}", opaque_ty ); } } else { span_bug!( - hir_ty.span, + hir.span(hir_ty.hir_id), "lowered return type of async fn is not OpaqueDef: {:?}", hir_ty ); diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index f9a94287fc39c..83a845dfee182 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -47,7 +47,7 @@ fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam) -> Body<'_ // Figure out what primary body this item has. let (body_id, return_ty_span, span_with_body) = match tcx.hir().get(id) { Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, decl, body_id, _, _), .. }) => { - (*body_id, decl.output.span(), None) + (*body_id, decl.output.span(|id| tcx.hir().span(id)), None) } Node::Item(hir::Item { kind: hir::ItemKind::Fn(hir::FnSig { decl, .. }, _, body_id), @@ -64,7 +64,7 @@ fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam) -> Body<'_ // Use the `Span` of the `Item/ImplItem/TraitItem` as the body span, // since the def span of a function does not include the body let span = tcx.hir().span_with_body(id); - (*body_id, decl.output.span(), Some(span)) + (*body_id, decl.output.span(|id| tcx.hir().span(id)), Some(span)) } Node::Item(hir::Item { kind: hir::ItemKind::Static(ty, _, body_id) | hir::ItemKind::Const(ty, body_id), @@ -74,7 +74,7 @@ fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam) -> Body<'_ | Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Const(ty, Some(body_id)), .. - }) => (*body_id, ty.span, None), + }) => (*body_id, tcx.hir().span(ty.hir_id), None), Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => { (*body, tcx.hir().span(*hir_id), None) } @@ -134,7 +134,7 @@ fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam) -> Body<'_ let opt_ty_info; let self_arg; if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) { - opt_ty_info = fn_decl.inputs.get(index).map(|ty| ty.span); + opt_ty_info = fn_decl.inputs.get(index).map(|ty| tcx.hir().span(ty.hir_id)); self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() { match fn_decl.implicit_self { hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm), diff --git a/compiler/rustc_mir_build/src/thir/cx/block.rs b/compiler/rustc_mir_build/src/thir/cx/block.rs index 9bf1e5cdd630e..0f90a6d6c4b30 100644 --- a/compiler/rustc_mir_build/src/thir/cx/block.rs +++ b/compiler/rustc_mir_build/src/thir/cx/block.rs @@ -72,7 +72,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { kind: Box::new(PatKind::AscribeUserType { ascription: thir::pattern::Ascription { user_ty: PatTyProj::from_user_type(user_ty), - user_ty_span: ty.span, + user_ty_span: self.tcx.hir().span(ty.hir_id), variance: ty::Variance::Covariant, }, subpattern: pattern, diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index b22b311bafe39..0bd8ad7d76804 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -1188,7 +1188,7 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { } fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) { - self.span = hir_ty.span; + self.span = self.tcx.hir().span(hir_ty.hir_id); if let Some(typeck_results) = self.maybe_typeck_results { // Types in bodies. if self.visit(typeck_results.node_type(hir_ty.hir_id)).is_break() { diff --git a/compiler/rustc_resolve/src/late/lifetimes.rs b/compiler/rustc_resolve/src/late/lifetimes.rs index 0b5de2f55b9d2..95b562d6d4b44 100644 --- a/compiler/rustc_resolve/src/late/lifetimes.rs +++ b/compiler/rustc_resolve/src/late/lifetimes.rs @@ -513,7 +513,8 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let (span, span_type) = if let Some(span) = lifetime_span { (span.shrink_to_hi(), ForLifetimeSpanType::TypeTail) } else { - (ty.span.shrink_to_lo(), ForLifetimeSpanType::TypeEmpty) + let ty_span = self.tcx.hir().span(ty.hir_id); + (ty_span.shrink_to_lo(), ForLifetimeSpanType::TypeEmpty) }; self.missing_named_lifetime_spots .push(MissingLifetimeSpot::HigherRanked { span, span_type }); @@ -551,7 +552,8 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { LifetimeName::Implicit => { // For types like `dyn Foo`, we should // generate a special form of elided. - span_bug!(ty.span, "object-lifetime-default expected, not implicit",); + let ty_span = self.tcx.hir().span(ty.hir_id); + span_bug!(ty_span, "object-lifetime-default expected, not implicit",); } LifetimeName::ImplicitObjectLifetimeDefault => { // If the user does not write *anything*, we @@ -1465,7 +1467,8 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { hir::TyKind::Rptr(lt, _) => { if lt.name.ident() == name { // include the trailing whitespace between the lifetime and type names - let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi()); + let input_span = self.tcx.hir().span(input.hir_id); + let lt_through_ty_span = lifetime.span.to(input_span.shrink_to_hi()); remove_use = Some( self.tcx .sess @@ -2267,12 +2270,13 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { possible_implied_output_region = gather.lifetimes.iter().cloned().next(); } + let input_span = self.tcx.hir().span(input.hir_id); ElisionFailureInfo { parent: body, index: i, lifetime_count: gather.lifetimes.len(), have_bound_regions: gather.have_bound_regions, - span: input.span, + span: input_span, } }) .collect(); 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 d912bdcfb7b25..00f6ab8565ada 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -822,7 +822,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { .iter() .map(|arg| match arg.kind { hir::TyKind::Tup(ref tys) => ArgKind::Tuple( - Some(arg.span), + Some(self.tcx.hir().span(arg.hir_id)), vec![("_".to_owned(), "_".to_owned()); tys.len()], ), _ => ArgKind::empty(), @@ -1777,6 +1777,7 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { format!("this could be changed to `{}: ?Sized`...", param.name.ident()), ); for sp in visitor.invalid_spans { + let sp = self.tcx.hir().span(sp); multispan.push_span_label( sp, format!( @@ -1832,7 +1833,7 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { /// `param: ?Sized` would be a valid constraint. struct FindTypeParam { param: rustc_span::Symbol, - invalid_spans: Vec, + invalid_spans: Vec, nested: bool, } @@ -1856,7 +1857,7 @@ impl<'v> Visitor<'v> for FindTypeParam { if path.segments.len() == 1 && path.segments[0].ident.name == self.param => { if !self.nested { - self.invalid_spans.push(ty.span); + self.invalid_spans.push(ty.hir_id); } } hir::TyKind::Path(_) => { 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 f768737de389a..be4a7a84dffd4 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -240,7 +240,8 @@ fn suggest_restriction( // ^^^^^^^^^^ get this to suggest `T` instead // There might be more than one `impl Trait`. - ty_spans.push(input.span); + let input_span = tcx.hir().span(input.hir_id); + ty_spans.push(input_span); } } } @@ -910,7 +911,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { { let body = hir.body(*body_id); if let hir::ExprKind::Block(blk, _) = &body.value.kind { - if sig.decl.output.span().overlaps(span) + if sig.decl.output.span(|id| self.tcx.hir().span(id)).overlaps(span) && blk.expr.is_none() && is_empty_tuple(trait_ref.self_ty()) { @@ -938,7 +939,11 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { _ => return None, }; - if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None } + if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { + Some(hir.span(ret_ty.hir_id)) + } else { + None + } } /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if @@ -1035,7 +1040,8 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { if let Some(ty_ret_ty) = typeck_results.node_type_opt(ret_ty.hir_id) { match ty_ret_ty.kind() { ty::Dynamic(predicates, _) => { - let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id); + let ret_ty_span = hir.span(ret_ty.hir_id); + let cause = ObligationCause::misc(ret_ty_span, ret_ty.hir_id); let param_env = ty::ParamEnv::empty(); only_never_return || ret_types.all(|returned_ty| { @@ -1053,11 +1059,12 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { }; let sm = self.tcx.sess.source_map(); + let ret_ty_span = hir.span(ret_ty.hir_id); let snippet = if let (true, hir::TyKind::TraitObject(..), Ok(snippet), true) = ( // Verify that we're dealing with a return `dyn Trait` - ret_ty.span.overlaps(span), + ret_ty_span.overlaps(span), &ret_ty.kind, - sm.span_to_snippet(ret_ty.span), + sm.span_to_snippet(ret_ty_span), // If any of the return types does not conform to the trait, then we can't // suggest `impl Trait` nor trait objects: it is a type mismatch error. all_returns_conform_to_trait, @@ -1082,14 +1089,14 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box`. suggest_trait_object_return_type_alternatives( err, - ret_ty.span, + ret_ty_span, trait_obj, is_object_safe, ); } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) { // Suggest `-> impl Trait`. err.span_suggestion( - ret_ty.span, + ret_ty_span, &format!( "use `impl {1}` as the return type, as all return paths are of type `{}`, \ which implements `{1}`", @@ -1113,7 +1120,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { .collect::>>() { // Add the suggestion for the return type. - suggestions.push((ret_ty.span, format!("Box", trait_obj))); + suggestions.push((ret_ty_span, format!("Box", trait_obj))); err.multipart_suggestion( "return a boxed trait object instead", suggestions, diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index 7de20e477fe04..dee34750a4925 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -361,14 +361,14 @@ fn object_safety_violation_for_method( (MethodViolationCode::ReferencesSelfInput(arg), Some(node)) => node .fn_decl() .and_then(|decl| decl.inputs.get(arg + 1)) - .map_or(method.ident.span, |arg| arg.span), + .map_or(method.ident.span, |arg| tcx.hir().span(arg.hir_id)), (MethodViolationCode::UndispatchableReceiver, Some(node)) => node .fn_decl() .and_then(|decl| decl.inputs.get(0)) - .map_or(method.ident.span, |arg| arg.span), - (MethodViolationCode::ReferencesSelfOutput, Some(node)) => { - node.fn_decl().map_or(method.ident.span, |decl| decl.output.span()) - } + .map_or(method.ident.span, |arg| tcx.hir().span(arg.hir_id)), + (MethodViolationCode::ReferencesSelfOutput, Some(node)) => node + .fn_decl() + .map_or(method.ident.span, |decl| decl.output.span(|id| tcx.hir().span(id))), _ => method.ident.span, }; (v, span) diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index dcbf91ef13075..7862e75c02a01 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -202,11 +202,13 @@ fn extend_cause_with_original_assoc_item_obligation<'tcx>( Some(hir::Item { kind: hir::ItemKind::Impl(impl_), .. }) => impl_.items, _ => return, }; - 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, - _ => tcx.hir().span(impl_item_ref.id.hir_id()), + let fix_span = |impl_item_ref: &hir::ImplItemRef<'_>| { + let hir_id = match tcx.hir().impl_item(impl_item_ref.id).kind { + hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::TyAlias(ty) => ty.hir_id, + _ => impl_item_ref.id.hir_id(), }; + tcx.hir().span(hir_id) + }; // It is fine to skip the binder as we don't care about regions here. match pred.kind().skip_binder() { @@ -336,7 +338,8 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) = item.map(|i| &i.kind) { - new_cause.make_mut().span = self_ty.span; + let self_ty_span = tcx.hir().span(self_ty.hir_id); + new_cause.make_mut().span = self_ty_span; } } traits::Obligation::with_depth( diff --git a/compiler/rustc_typeck/src/astconv/errors.rs b/compiler/rustc_typeck/src/astconv/errors.rs index b5404c3a15ce0..241e408479031 100644 --- a/compiler/rustc_typeck/src/astconv/errors.rs +++ b/compiler/rustc_typeck/src/astconv/errors.rs @@ -115,10 +115,14 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { hir::GenericArg::Type(ty) => match ty.kind { hir::TyKind::Tup(t) => t .iter() - .map(|e| sess.source_map().span_to_snippet(e.span)) + .map(|e| sess + .source_map() + .span_to_snippet(self.tcx().hir().span(e.hir_id))) .collect::, _>>() .map(|a| a.join(", ")), - _ => sess.source_map().span_to_snippet(ty.span), + _ => sess + .source_map() + .span_to_snippet(self.tcx().hir().span(ty.hir_id)), } .map(|s| format!("({})", s)) .ok(), @@ -131,7 +135,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .iter() .find_map(|b| match (b.ident.name == sym::Output, &b.kind) { (true, hir::TypeBindingKind::Equality { ty }) => { - sess.source_map().span_to_snippet(ty.span).ok() + sess.source_map() + .span_to_snippet(self.tcx().hir().span(ty.hir_id)) + .ok() } _ => None, }) diff --git a/compiler/rustc_typeck/src/astconv/mod.rs b/compiler/rustc_typeck/src/astconv/mod.rs index 6345e1cb08722..6c2bde7a91b1d 100644 --- a/compiler/rustc_typeck/src/astconv/mod.rs +++ b/compiler/rustc_typeck/src/astconv/mod.rs @@ -438,7 +438,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { if let (hir::TyKind::Infer, false) = (&ty.kind, self.astconv.allow_ty_infer()) { - self.inferred_params.push(ty.span); + let ty_span = tcx.hir().span(ty.hir_id); + self.inferred_params.push(ty_span); tcx.ty_error().into() } else { self.astconv.ast_ty_to_ty(&ty).into() @@ -1869,7 +1870,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } err_for_ty = true; has_err = true; - (ty.span, "type") + let ty_span = self.tcx().hir().span(ty.hir_id); + (ty_span, "type") } hir::GenericArg::Const(ct) => { if err_for_ct { @@ -2117,7 +2119,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .. })) = tcx.hir().get_if_local(def_id) { - err.span_note(impl_.self_ty.span, "not a concrete type"); + let self_ty_span = tcx.hir().span(impl_.self_ty.hir_id); + err.span_note(self_ty_span, "not a concrete type"); } err.emit(); tcx.ty_error() @@ -2168,6 +2171,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.kind); let tcx = self.tcx(); + let ast_ty_span = tcx.hir().span(ast_ty.hir_id); let result_ty = match ast_ty.kind { hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)), @@ -2185,7 +2189,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t))) } hir::TyKind::BareFn(ref bf) => { - require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span); + require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty_span); tcx.mk_fn_ptr(self.ty_of_fn( bf.unsafety, @@ -2197,7 +2201,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { )) } hir::TyKind::TraitObject(ref bounds, ref lifetime) => { - self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed) + self.conv_object_ty_poly_trait_ref(ast_ty_span, bounds, lifetime, borrowed) } hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => { debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path); @@ -2224,7 +2228,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } else { Res::Err }; - self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false) + self.associated_path_to_ty(ast_ty.hir_id, ast_ty_span, ty, res, segment, false) .map(|(ty, _, _)| ty) .unwrap_or_else(|_| tcx.ty_error()) } @@ -2245,10 +2249,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let length_def_id = tcx.hir().local_def_id(length.hir_id); let length = ty::Const::from_anon_const(tcx, length_def_id); let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length)); - self.normalize_ty(ast_ty.span, array_ty) + self.normalize_ty(ast_ty_span, array_ty) } hir::TyKind::Typeof(ref _e) => { - tcx.sess.emit_err(TypeofReservedKeywordUsed { span: ast_ty.span }); + tcx.sess.emit_err(TypeofReservedKeywordUsed { span: ast_ty_span }); tcx.ty_error() } hir::TyKind::Infer => { @@ -2256,14 +2260,14 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // values in a ExprKind::Closure, or as // the type of local variables. Both of these cases are // handled specially and will not descend into this routine. - self.ty_infer(None, ast_ty.span) + self.ty_infer(None, ast_ty_span) } hir::TyKind::Err => tcx.ty_error(), }; debug!("ast_ty_to_ty: result_ty={:?}", result_ty); - self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span); + self.record_ty(ast_ty.hir_id, result_ty, ast_ty_span); result_ty } @@ -2319,7 +2323,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option>) -> Ty<'tcx> { match ty.kind { hir::TyKind::Infer if expected_ty.is_some() => { - self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span); + let ty_span = self.tcx().hir().span(ty.hir_id); + self.record_ty(ty.hir_id, expected_ty.unwrap(), ty_span); expected_ty.unwrap() } _ => self.ast_ty_to_ty(ty), @@ -2391,7 +2396,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| { struct_span_err!( tcx.sess, - decl.output.span(), + decl.output.span(|id| tcx.hir().span(id)), E0581, "return type references {}, which is not constrained by the fn input types", br_name diff --git a/compiler/rustc_typeck/src/check/_match.rs b/compiler/rustc_typeck/src/check/_match.rs index 08185bd968af6..cbbca3b2a0123 100644 --- a/compiler/rustc_typeck/src/check/_match.rs +++ b/compiler/rustc_typeck/src/check/_match.rs @@ -30,7 +30,7 @@ macro_rules! create_maybe_get_coercion_reason { // check that the `if` expr without `else` is the fn body's expr if expr.span == sp { return self.get_fn_decl(hir_id).and_then(|(fn_decl, _)| { - let span = fn_decl.output.span(); + let span = fn_decl.output.span(|id| self.tcx.hir().span(id)); let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok()?; Some(( span, diff --git a/compiler/rustc_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index 1e9aba87e94cc..b00bd52930407 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -89,11 +89,14 @@ pub(super) fn check_fn<'a, 'tcx>( let declared_ret_ty = fn_sig.output(); - let revealed_ret_ty = - fcx.instantiate_opaque_types_from_value(fn_id, declared_ret_ty, decl.output.span()); + let revealed_ret_ty = fcx.instantiate_opaque_types_from_value( + fn_id, + declared_ret_ty, + decl.output.span(|id| hir.span(id)), + ); debug!("check_fn: declared_ret_ty: {}, revealed_ret_ty: {}", declared_ret_ty, revealed_ret_ty); fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(revealed_ret_ty))); - fcx.ret_type_span = Some(decl.output.span()); + fcx.ret_type_span = Some(decl.output.span(|id| hir.span(id))); if let ty::Opaque(..) = declared_ret_ty.kind() { fcx.ret_coercion_impl_trait = Some(declared_ret_ty); } @@ -176,7 +179,7 @@ pub(super) fn check_fn<'a, 'tcx>( let inputs_fn = fn_sig.inputs().iter().copied(); for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() { // Check the pattern. - let ty_span = try { inputs_hir?.get(idx)?.span }; + let ty_span = try { hir.span(inputs_hir?.get(idx)?.hir_id) }; fcx.check_pat_top(¶m.pat, param_ty, ty_span, false); // Check that argument is Sized. @@ -207,9 +210,17 @@ pub(super) fn check_fn<'a, 'tcx>( // the tail expression's type so that the suggestion will be correct, but ignore all other // possible cases. fcx.check_expr(&body.value); - fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType); + fcx.require_type_is_sized( + declared_ret_ty, + decl.output.span(|id| tcx.hir().span(id)), + traits::SizedReturnType, + ); } else { - fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType); + fcx.require_type_is_sized( + declared_ret_ty, + decl.output.span(|id| hir.span(id)), + traits::SizedReturnType, + ); fcx.check_return_expr(&body.value); } fcx.in_tail_expr = false; @@ -273,7 +284,7 @@ pub(super) fn check_fn<'a, 'tcx>( if main_id == fn_id { let substs = tcx.mk_substs_trait(declared_ret_ty, &[]); let trait_ref = ty::TraitRef::new(term_id, substs); - let return_ty_span = decl.output.span(); + let return_ty_span = decl.output.span(|id| hir.span(id)); let cause = traits::ObligationCause::new( return_ty_span, fn_id, @@ -294,7 +305,7 @@ pub(super) fn check_fn<'a, 'tcx>( if panic_impl_did == hir.local_def_id(fn_id).to_def_id() { if let Some(panic_info_did) = tcx.lang_items().panic_info() { if *declared_ret_ty.kind() != ty::Never { - sess.span_err(decl.output.span(), "return type should be `!`"); + sess.span_err(decl.output.span(|id| hir.span(id)), "return type should be `!`"); } let inputs = fn_sig.inputs(); @@ -313,7 +324,10 @@ pub(super) fn check_fn<'a, 'tcx>( }; if !arg_is_panic_info { - sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`"); + sess.span_err( + hir.span(decl.inputs[0].hir_id), + "argument should be `&PanicInfo`", + ); } if let Node::Item(item) = hir.get(fn_id) { @@ -338,7 +352,7 @@ pub(super) fn check_fn<'a, 'tcx>( if alloc_error_handler_did == hir.local_def_id(fn_id).to_def_id() { if let Some(alloc_layout_did) = tcx.lang_items().alloc_layout() { if *declared_ret_ty.kind() != ty::Never { - sess.span_err(decl.output.span(), "return type should be `!`"); + sess.span_err(decl.output.span(|id| hir.span(id)), "return type should be `!`"); } let inputs = fn_sig.inputs(); @@ -350,7 +364,10 @@ pub(super) fn check_fn<'a, 'tcx>( }; if !arg_is_alloc_layout { - sess.span_err(decl.inputs[0].span, "argument should be `Layout`"); + sess.span_err( + hir.span(decl.inputs[0].hir_id), + "argument should be `Layout`", + ); } if let Node::Item(item) = hir.get(fn_id) { diff --git a/compiler/rustc_typeck/src/check/closure.rs b/compiler/rustc_typeck/src/check/closure.rs index 431e6d70ff35c..a2433eb856ed9 100644 --- a/compiler/rustc_typeck/src/check/closure.rs +++ b/compiler/rustc_typeck/src/check/closure.rs @@ -499,26 +499,27 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .zip(expected_sigs.liberated_sig.inputs()) // `liberated_sig` is E'. { + let ty_span = self.tcx.hir().span(hir_ty.hir_id); // Instantiate (this part of..) S to S', i.e., with fresh variables. let (supplied_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars( - hir_ty.span, + ty_span, LateBoundRegionConversionTime::FnCall, supplied_sig.inputs().rebind(supplied_ty), ); // recreated from (*) above // Check that E' = S'. - let cause = self.misc(hir_ty.span); + let cause = self.misc(ty_span); let InferOk { value: (), obligations } = self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?; all_obligations.extend(obligations); } let (supplied_output_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars( - decl.output.span(), + decl.output.span(|id| self.tcx.hir().span(id)), LateBoundRegionConversionTime::FnCall, supplied_sig.output(), ); - let cause = &self.misc(decl.output.span()); + let cause = &self.misc(decl.output.span(|id| self.tcx.hir().span(id))); let InferOk { value: (), obligations } = self .at(cause, self.param_env) .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?; @@ -563,11 +564,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // easily (and locally) prove that we // *have* reported an // error. --nikomatsakis - astconv.ty_infer(None, decl.output.span()) + astconv.ty_infer(None, decl.output.span(|id| self.tcx.hir().span(id))) }) } - _ => astconv.ty_infer(None, decl.output.span()), + _ => astconv.ty_infer(None, decl.output.span(|id| self.tcx.hir().span(id))), }, }; diff --git a/compiler/rustc_typeck/src/check/coercion.rs b/compiler/rustc_typeck/src/check/coercion.rs index 32b3d0b059545..5934d7ecec7fe 100644 --- a/compiler/rustc_typeck/src/check/coercion.rs +++ b/compiler/rustc_typeck/src/check/coercion.rs @@ -1527,7 +1527,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { sp: Span, fn_output: &hir::FnRetTy<'_>, ) { - let return_sp = fn_output.span(); + let return_sp = fn_output.span(|id| fcx.tcx.hir().span(id)); err.span_label(return_sp, "expected because this return type..."); err.span_label( sp, diff --git a/compiler/rustc_typeck/src/check/compare_method.rs b/compiler/rustc_typeck/src/check/compare_method.rs index 5700fae8f6b69..1bbd89a41d8de 100644 --- a/compiler/rustc_typeck/src/check/compare_method.rs +++ b/compiler/rustc_typeck/src/check/compare_method.rs @@ -424,7 +424,9 @@ fn extract_spans_for_error_reporting<'a, 'tcx>( _ => false, } }) - .map(|(ref impl_arg, ref trait_arg)| (impl_arg.span, Some(trait_arg.span))) + .map(|(ref impl_arg, ref trait_arg)| { + (tcx.hir().span(impl_arg.hir_id), Some(tcx.hir().span(trait_arg.hir_id))) + }) .unwrap_or_else(|| (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))) } else { (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)) @@ -452,7 +454,10 @@ fn extract_spans_for_error_reporting<'a, 'tcx>( .sub(trait_arg_ty, impl_arg_ty) { Ok(_) => None, - Err(_) => Some((impl_arg.span, Some(trait_arg.span))), + Err(_) => Some(( + tcx.hir().span(impl_arg.hir_id), + Some(tcx.hir().span(trait_arg.hir_id)), + )), }) .unwrap_or_else(|| { if infcx @@ -460,7 +465,10 @@ fn extract_spans_for_error_reporting<'a, 'tcx>( .sup(trait_sig.output(), impl_sig.output()) .is_err() { - (impl_m_output.span(), Some(trait_m_output.span())) + ( + impl_m_output.span(|id| tcx.hir().span(id)), + Some(trait_m_output.span(|id| tcx.hir().span(id))), + ) } else { (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)) } @@ -716,13 +724,14 @@ fn compare_number_of_method_arguments<'tcx>( TraitItemKind::Fn(ref trait_m_sig, _) => { let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 }; if let Some(arg) = trait_m_sig.decl.inputs.get(pos) { + let arg_span = tcx.hir().span(arg.hir_id); Some(if pos == 0 { - arg.span + arg_span } else { Span::new( - trait_m_sig.decl.inputs[0].span.lo(), - arg.span.hi(), - arg.span.ctxt(), + tcx.hir().span(trait_m_sig.decl.inputs[0].hir_id).lo(), + arg_span.hi(), + arg_span.ctxt(), ) }) } else { @@ -739,13 +748,14 @@ fn compare_number_of_method_arguments<'tcx>( ImplItemKind::Fn(ref impl_m_sig, _) => { let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 }; if let Some(arg) = impl_m_sig.decl.inputs.get(pos) { + let arg_span = tcx.hir().span(arg.hir_id); if pos == 0 { - arg.span + arg_span } else { Span::new( - impl_m_sig.decl.inputs[0].span.lo(), - arg.span.hi(), - arg.span.ctxt(), + tcx.hir().span(impl_m_sig.decl.inputs[0].hir_id).lo(), + arg_span.hi(), + arg_span.ctxt(), ) } } else { @@ -880,7 +890,7 @@ fn compare_synthetic_generics<'tcx>( hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs, _ => unreachable!(), }; - struct Visitor(Option, hir::def_id::DefId); + struct Visitor(Option, hir::def_id::DefId); impl<'v> intravisit::Visitor<'v> for Visitor { fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) { intravisit::walk_ty(self, ty); @@ -889,7 +899,7 @@ fn compare_synthetic_generics<'tcx>( { if let Res::Def(DefKind::TyParam, def_id) = path.res { if def_id == self.1 { - self.0 = Some(ty.span); + self.0 = Some(ty.hir_id); } } } @@ -906,7 +916,7 @@ fn compare_synthetic_generics<'tcx>( for ty in input_tys { intravisit::Visitor::visit_ty(&mut visitor, ty); } - let span = visitor.0?; + let span = tcx.hir().span(visitor.0?); let bounds = impl_m.generics.params.iter().find_map(|param| match param.kind { @@ -1002,7 +1012,7 @@ crate fn compare_const_impl<'tcx>( // Locate the Span containing just the type of the offending impl match tcx.hir().expect_impl_item(impl_c_hir_id).kind { - ImplItemKind::Const(ref ty, _) => cause.make_mut().span = ty.span, + ImplItemKind::Const(ref ty, _) => cause.make_mut().span = tcx.hir().span(ty.hir_id), _ => bug!("{:?} is not a impl const", impl_c), } @@ -1020,7 +1030,7 @@ crate fn compare_const_impl<'tcx>( let trait_c_span = trait_c_hir_id.map(|trait_c_hir_id| { // Add a label to the Span containing just the type of the const match tcx.hir().expect_trait_item(trait_c_hir_id).kind { - TraitItemKind::Const(ref ty, _) => ty.span, + TraitItemKind::Const(ref ty, _) => tcx.hir().span(ty.hir_id), _ => bug!("{:?} is not a trait const", trait_c), } }); diff --git a/compiler/rustc_typeck/src/check/demand.rs b/compiler/rustc_typeck/src/check/demand.rs index f9f67769e96a4..215037b1d8dcc 100644 --- a/compiler/rustc_typeck/src/check/demand.rs +++ b/compiler/rustc_typeck/src/check/demand.rs @@ -163,7 +163,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { if init.hir_id == expr.hir_id { // Point at `let` assignment type. - err.span_label(ty.span, "expected due to this"); + let ty_span = self.tcx.hir().span(ty.hir_id); + err.span_label(ty_span, "expected due to this"); } } } diff --git a/compiler/rustc_typeck/src/check/expr.rs b/compiler/rustc_typeck/src/check/expr.rs index 9fb8c0f89c280..72926c5d5daf9 100644 --- a/compiler/rustc_typeck/src/check/expr.rs +++ b/compiler/rustc_typeck/src/check/expr.rs @@ -688,7 +688,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self, &cause, &mut |db| { - let span = fn_decl.output.span(); + let span = fn_decl.output.span(|id| self.tcx.hir().span(id)); if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { db.span_label( span, @@ -1038,7 +1038,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { // Defer other checks until we're done type checking. let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut(); - match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) { + let t_span = self.tcx.hir().span(t.hir_id); + match cast::CastCheck::new(self, e, t_expr, t_cast, t_span, expr.span) { Ok(cast_check) => { deferred_cast_checks.push(cast_check); t_cast diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs index 92f166c1deb77..f7417b354e7a3 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs @@ -458,7 +458,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub fn to_ty(&self, ast_t: &hir::Ty<'_>) -> Ty<'tcx> { let t = AstConv::ast_ty_to_ty(self, ast_t); - self.register_wf_obligation(t.into(), ast_t.span, traits::MiscObligation); + let ast_t_span = self.tcx.hir().span(ast_t.hir_id); + self.register_wf_obligation(t.into(), ast_t_span, traits::MiscObligation); t } diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs index 468af6842bbef..95d485b8d4fbe 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs @@ -441,7 +441,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { qpath: &QPath<'_>, hir_id: hir::HirId, ) -> Option<(&'tcx ty::VariantDef, Ty<'tcx>)> { - let path_span = qpath.qself_span(); + let path_span = qpath.qself_span(|id| self.tcx.hir().span(id)); let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, hir_id); let variant = match def { Res::Err => { @@ -531,7 +531,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Does the expected pattern type originate from an expression and what is the span? let (origin_expr, ty_span) = match (local.ty, local.init) { - (Some(ty), _) => (false, Some(ty.span)), // Bias towards the explicit user type. + (Some(ty), _) => (false, Some(self.tcx.hir().span(ty.hir_id))), // Bias towards the explicit user type. (_, Some(init)) => (true, Some(init.span)), // No explicit type; so use the scrutinee. _ => (false, None), // We have `let $pat;`, so the expected type is unconstrained. }; @@ -675,7 +675,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { 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(); + let ret_sp = decl.output.span(|id| self.tcx.hir().span(id)); if let Some(block_sp) = self.parent_item_span(blk.hir_id) { // HACK: on some cases (`ui/liveness/liveness-issue-2163.rs`) the // output would otherwise be incorrect and even misleading. Make sure @@ -1011,7 +1011,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ty = AstConv::ast_ty_to_ty(self, hir_ty); let ty = self.resolve_vars_if_possible(ty); if ty == predicate.self_ty() { - error.obligation.cause.make_mut().span = hir_ty.span; + error.obligation.cause.make_mut().span = + self.tcx.hir().span(hir_ty.hir_id); } } } diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs b/compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs index 9f15993e4718c..8967a9e4221a4 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs @@ -460,7 +460,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Only point to return type if the expected type is the return type, as if they // are not, the expectation must have been caused by something else. debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind); - let sp = ty.span; + let sp = self.tcx.hir().span(ty.hir_id); let ty = AstConv::ast_ty_to_ty(self, ty); debug!("suggest_missing_return_type: return type {:?}", ty); debug!("suggest_missing_return_type: expected type {:?}", ty); diff --git a/compiler/rustc_typeck/src/check/gather_locals.rs b/compiler/rustc_typeck/src/check/gather_locals.rs index f00ddde4d6e40..bae2953e20a51 100644 --- a/compiler/rustc_typeck/src/check/gather_locals.rs +++ b/compiler/rustc_typeck/src/check/gather_locals.rs @@ -59,7 +59,8 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> { let o_ty = self.fcx.to_ty(&ty); let revealed_ty = if self.fcx.tcx.features().impl_trait_in_bindings { - self.fcx.instantiate_opaque_types_from_value(self.parent_id, o_ty, ty.span) + let ty_span = self.fcx.tcx.hir().span(ty.hir_id); + self.fcx.instantiate_opaque_types_from_value(self.parent_id, o_ty, ty_span) } else { o_ty }; diff --git a/compiler/rustc_typeck/src/check/method/suggest.rs b/compiler/rustc_typeck/src/check/method/suggest.rs index 125daf80f8dc7..77abba94eb3d1 100644 --- a/compiler/rustc_typeck/src/check/method/suggest.rs +++ b/compiler/rustc_typeck/src/check/method/suggest.rs @@ -363,7 +363,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // ^^^^ span.to(ty .as_ref() - .map(|ty| ty.span) + .map(|ty| tcx.hir().span(ty.hir_id)) .unwrap_or(span)), &msg, format!("{}: {}", snippet, concrete_type), @@ -1057,7 +1057,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && self_first_arg { if let Some(ty) = fn_sig.decl.inputs.get(0) { - arbitrary_rcvr.push(ty.span); + let ty_span = self.tcx.hir().span(ty.hir_id); + arbitrary_rcvr.push(ty_span); } return false; } diff --git a/compiler/rustc_typeck/src/check/mod.rs b/compiler/rustc_typeck/src/check/mod.rs index ebebc8de6c209..d577f5f9a1a1c 100644 --- a/compiler/rustc_typeck/src/check/mod.rs +++ b/compiler/rustc_typeck/src/check/mod.rs @@ -703,9 +703,10 @@ fn binding_opaque_type_cycle_error( .. }) => { let pat_span = tcx.hir().span(pat.hir_id); + let ty_span = tcx.hir().span(ty.hir_id); err.span_label(pat_span, "this binding might not have a concrete type"); err.span_suggestion_verbose( - ty.span.shrink_to_hi(), + ty_span.shrink_to_hi(), "set the binding to a value for a concrete type to be resolved", " = /* value */".to_string(), Applicability::HasPlaceholders, diff --git a/compiler/rustc_typeck/src/check/wfcheck.rs b/compiler/rustc_typeck/src/check/wfcheck.rs index 97c1a64c80366..50cb7570aec51 100644 --- a/compiler/rustc_typeck/src/check/wfcheck.rs +++ b/compiler/rustc_typeck/src/check/wfcheck.rs @@ -145,10 +145,12 @@ pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) { check_item_fn(tcx, item.hir_id(), item.ident, sig.decl); } hir::ItemKind::Static(ref ty, ..) => { - check_item_type(tcx, item.hir_id(), ty.span, false); + let ty_span = tcx.hir().span(ty.hir_id); + check_item_type(tcx, item.hir_id(), ty_span, false); } hir::ItemKind::Const(ref ty, ..) => { - check_item_type(tcx, item.hir_id(), ty.span, false); + let ty_span = tcx.hir().span(ty.hir_id); + check_item_type(tcx, item.hir_id(), ty_span, false); } hir::ItemKind::ForeignMod { items, .. } => { for it in items.iter() { @@ -158,7 +160,8 @@ pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) { check_item_fn(tcx, it.hir_id(), it.ident, decl) } hir::ForeignItemKind::Static(ref ty, ..) => { - check_item_type(tcx, it.hir_id(), ty.span, true) + let ty_span = tcx.hir().span(ty.hir_id); + check_item_type(tcx, it.hir_id(), ty_span, true) } hir::ForeignItemKind::Type => (), } @@ -226,17 +229,20 @@ fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty)) if could_be_self(trait_def_id, ty) => { - trait_should_be_self.push(ty.span) + let ty_span = tcx.hir().span(ty.hir_id); + trait_should_be_self.push(ty_span) } hir::TraitItemKind::Fn(sig, _) => { for ty in sig.decl.inputs { if could_be_self(trait_def_id, ty) { - trait_should_be_self.push(ty.span); + let ty_span = tcx.hir().span(ty.hir_id); + trait_should_be_self.push(ty_span); } } match sig.decl.output { hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => { - trait_should_be_self.push(ty.span); + let ty_span = tcx.hir().span(ty.hir_id); + trait_should_be_self.push(ty_span); } _ => {} } @@ -307,9 +313,10 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) { } }; if let Some(unsupported_type) = err { + let hir_ty_span = tcx.hir().span(hir_ty.hir_id); if is_ptr { tcx.sess.span_err( - hir_ty.span, + hir_ty_span, &format!( "using {} as const generic parameters is forbidden", unsupported_type @@ -318,7 +325,7 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) { } else { tcx.sess .struct_span_err( - hir_ty.span, + hir_ty_span, &format!( "{} is forbidden as the type of a const generic parameter", unsupported_type @@ -336,20 +343,21 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) { // We use the same error code in both branches, because this is really the same // issue: we just special-case the message for type parameters to make it // clearer. + let hir_ty_span = tcx.hir().span(hir_ty.hir_id); if let ty::Param(_) = ty.peel_refs().kind() { // Const parameters may not have type parameters as their types, // because we cannot be sure that the type parameter derives `PartialEq` // and `Eq` (just implementing them is not enough for `structural_match`). struct_span_err!( tcx.sess, - hir_ty.span, + hir_ty_span, E0741, "`{}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \ used as the type of a const parameter", ty, ) .span_label( - hir_ty.span, + hir_ty_span, format!("`{}` may not derive both `PartialEq` and `Eq`", ty), ) .note( @@ -360,14 +368,14 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) { } else { struct_span_err!( tcx.sess, - hir_ty.span, + hir_ty_span, E0741, "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \ the type of a const parameter", ty, ) .span_label( - hir_ty.span, + hir_ty_span, format!("`{}` doesn't derive both `PartialEq` and `Eq`", ty), ) .emit(); @@ -687,9 +695,10 @@ fn check_impl<'tcx>( let self_ty = fcx.tcx.type_of(item.def_id); let item_span = tcx.hir().span_with_body(item.hir_id()); let self_ty = fcx.normalize_associated_types_in(item_span, self_ty); + let self_ty_span = tcx.hir().span(ast_self_ty.hir_id); fcx.register_wf_obligation( self_ty.into(), - ast_self_ty.span, + self_ty_span, ObligationCauseCode::MiscObligation, ); } @@ -882,21 +891,29 @@ fn check_fn_or_method<'fcx, 'tcx>( let sig = fcx.normalize_associated_types_in(span, sig); let sig = fcx.tcx.liberate_late_bound_regions(def_id, sig); - for (&input_ty, span) in sig.inputs().iter().zip(hir_decl.inputs.iter().map(|t| t.span)) { + for (&input_ty, span) in + sig.inputs().iter().zip(hir_decl.inputs.iter().map(|t| tcx.hir().span(t.hir_id))) + { fcx.register_wf_obligation(input_ty.into(), span, ObligationCauseCode::MiscObligation); } implied_bounds.extend(sig.inputs()); fcx.register_wf_obligation( sig.output().into(), - hir_decl.output.span(), + hir_decl.output.span(|id| tcx.hir().span(id)), ObligationCauseCode::ReturnType, ); // FIXME(#25759) return types should not be implied bounds implied_bounds.push(sig.output()); - check_where_clauses(tcx, fcx, span, def_id, Some((sig.output(), hir_decl.output.span()))); + check_where_clauses( + tcx, + fcx, + span, + def_id, + Some((sig.output(), hir_decl.output.span(|id| tcx.hir().span(id)))), + ); } /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions @@ -1054,7 +1071,7 @@ fn check_method_receiver<'fcx, 'tcx>( return; } - let span = fn_sig.decl.inputs[0].span; + let span = fcx.tcx.hir().span(fn_sig.decl.inputs[0].hir_id); let sig = fcx.tcx.fn_sig(method.def_id); let sig = fcx.normalize_associated_types_in(span, sig); @@ -1398,11 +1415,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .fields() .iter() .map(|field| { + let span = self.tcx.hir().span(field.ty.hir_id); let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id)); - let field_ty = self.normalize_associated_types_in(field.ty.span, field_ty); + let field_ty = self.normalize_associated_types_in(span, field_ty); let field_ty = self.resolve_vars_if_possible(field_ty); debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty); - AdtField { ty: field_ty, span: field.ty.span } + AdtField { ty: field_ty, span } }) .collect(); AdtVariant { fields, explicit_discr: None } diff --git a/compiler/rustc_typeck/src/check/writeback.rs b/compiler/rustc_typeck/src/check/writeback.rs index 65f2c5af440cf..5148289c573ea 100644 --- a/compiler/rustc_typeck/src/check/writeback.rs +++ b/compiler/rustc_typeck/src/check/writeback.rs @@ -329,8 +329,9 @@ impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) { intravisit::walk_ty(self, hir_ty); + let ty_span = self.tcx().hir().span(hir_ty.hir_id); let ty = self.fcx.node_ty(hir_ty.hir_id); - let ty = self.resolve(ty, &hir_ty.span); + let ty = self.resolve(ty, &ty_span); self.write_ty_to_typeck_results(hir_ty.hir_id, ty); } } diff --git a/compiler/rustc_typeck/src/coherence/builtin.rs b/compiler/rustc_typeck/src/coherence/builtin.rs index 5b44cb7eae516..a7820110c0776 100644 --- a/compiler/rustc_typeck/src/coherence/builtin.rs +++ b/compiler/rustc_typeck/src/coherence/builtin.rs @@ -54,7 +54,7 @@ fn visit_implementation_of_drop(tcx: TyCtxt<'_>, impl_did: LocalDefId) { let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_did); let sp = match tcx.hir().expect_item(impl_hir_id).kind { - ItemKind::Impl(ref impl_) => impl_.self_ty.span, + ItemKind::Impl(ref impl_) => tcx.hir().span(impl_.self_ty.hir_id), _ => bug!("expected Drop impl item"), }; @@ -98,8 +98,11 @@ fn visit_implementation_of_copy(tcx: TyCtxt<'_>, impl_did: LocalDefId) { } Err(CopyImplementationError::NotAnAdt) => { let item = tcx.hir().expect_item(impl_hir_id); - let span = - if let ItemKind::Impl(ref impl_) = item.kind { impl_.self_ty.span } else { span }; + let span = if let ItemKind::Impl(ref impl_) = item.kind { + tcx.hir().span(impl_.self_ty.hir_id) + } else { + span + }; tcx.sess.emit_err(CopyImplOnNonAdt { span }); } diff --git a/compiler/rustc_typeck/src/coherence/inherent_impls.rs b/compiler/rustc_typeck/src/coherence/inherent_impls.rs index b831b9da58f57..7497f91eb2981 100644 --- a/compiler/rustc_typeck/src/coherence/inherent_impls.rs +++ b/compiler/rustc_typeck/src/coherence/inherent_impls.rs @@ -333,14 +333,15 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Error(_) => {} _ => { + let ty_span = self.tcx.hir().span(ty.hir_id); let mut err = struct_span_err!( self.tcx.sess, - ty.span, + ty_span, E0118, "no nominal type found for inherent implementation" ); - err.span_label(ty.span, "impl requires a nominal type") + err.span_label(ty_span, "impl requires a nominal type") .note("either implement a trait on it or create a newtype to wrap it instead"); if let ty::Ref(_, subty, _) = self_ty.kind() { diff --git a/compiler/rustc_typeck/src/coherence/orphan.rs b/compiler/rustc_typeck/src/coherence/orphan.rs index 02e5b6613f9d6..fd3287ea50a78 100644 --- a/compiler/rustc_typeck/src/coherence/orphan.rs +++ b/compiler/rustc_typeck/src/coherence/orphan.rs @@ -74,7 +74,8 @@ impl ItemLikeVisitor<'v> for OrphanChecker<'tcx> { let msg = format!("{} is not defined in the current crate{}", ty, postfix); if *is_target_ty { // Point at `D` in `impl for C in D` - err.span_label(self_ty.span, &msg); + let self_ty_span = self.tcx.hir().span(self_ty.hir_id); + err.span_label(self_ty_span, &msg); } else { // Point at `C` in `impl for C in D` err.span_label(tr.path.span, &msg); diff --git a/compiler/rustc_typeck/src/collect.rs b/compiler/rustc_typeck/src/collect.rs index b59a12ae9dc19..bfbc77f5830c4 100644 --- a/compiler/rustc_typeck/src/collect.rs +++ b/compiler/rustc_typeck/src/collect.rs @@ -114,7 +114,7 @@ pub struct ItemCtxt<'tcx> { /////////////////////////////////////////////////////////////////////////// #[derive(Default)] -crate struct PlaceholderHirTyCollector(crate Vec); +crate struct PlaceholderHirTyCollector(crate Vec); impl<'v> Visitor<'v> for PlaceholderHirTyCollector { type Map = intravisit::ErasedMap<'v>; @@ -124,7 +124,7 @@ impl<'v> Visitor<'v> for PlaceholderHirTyCollector { } fn visit_ty(&mut self, t: &'v hir::Ty<'v>) { if let hir::TyKind::Infer = t.kind { - self.0.push(t.span); + self.0.push(t.hir_id); } intravisit::walk_ty(self, t) } @@ -141,7 +141,7 @@ crate fn placeholder_type_error( tcx: TyCtxt<'tcx>, span: Option, generics: &[hir::GenericParam<'_>], - placeholder_types: Vec, + placeholder_types: Vec, suggest: bool, hir_ty: Option<&hir::Ty<'_>>, ) { @@ -150,8 +150,10 @@ crate fn placeholder_type_error( } let type_name = generics.next_type_param_name(None); - let mut sugg: Vec<_> = - placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect(); + let mut sugg: Vec<_> = placeholder_types + .iter() + .map(|sp| (tcx.hir().span(*sp), (*type_name).to_string())) + .collect(); if generics.is_empty() { if let Some(span) = span { @@ -175,6 +177,7 @@ crate fn placeholder_type_error( )); } + let placeholder_types = placeholder_types.into_iter().map(|id| tcx.hir().span(id)).collect(); let mut err = bad_placeholder_type(tcx, placeholder_types); // Suggest, but only if it is not a function in const or static @@ -1674,7 +1677,8 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> { let mut visitor = PlaceholderHirTyCollector::default(); visitor.visit_ty(ty); - let mut diag = bad_placeholder_type(tcx, visitor.0); + let spans = visitor.0.into_iter().map(|id| tcx.hir().span(id)).collect(); + let mut diag = bad_placeholder_type(tcx, spans); let ret_ty = fn_sig.output(); if ret_ty != tcx.ty_error() { if !ret_ty.is_closure() { @@ -1685,8 +1689,9 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> { ty::FnDef(..) => ret_ty.fn_sig(tcx).to_string(), _ => ret_ty.to_string(), }; + let ty_span = tcx.hir().span(ty.hir_id); diag.span_suggestion( - ty.span, + ty_span, "replace with the correct return type", ret_ty_str, Applicability::MaybeIncorrect, @@ -2087,7 +2092,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericP // users who never wrote `where Type:,` themselves, to // compiler/tooling bugs from not handling WF predicates. } else { - let span = bound_pred.bounded_ty.span; + let span = tcx.hir().span(bound_pred.bounded_ty.hir_id); let re_root_empty = tcx.lifetimes.re_root_empty; let predicate = ty::Binder::bind(ty::PredicateKind::TypeOutlives( ty::OutlivesPredicate(ty, re_root_empty), @@ -2410,14 +2415,15 @@ fn compute_sig_of_foreign_fn_decl<'tcx>( { let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| { if ty.is_simd() { + let ty_span = tcx.hir().span(ast_ty.hir_id); let snip = tcx .sess .source_map() - .span_to_snippet(ast_ty.span) + .span_to_snippet(ty_span) .map_or_else(|_| String::new(), |s| format!(" `{}`", s)); tcx.sess .struct_span_err( - ast_ty.span, + ty_span, &format!( "use of SIMD type{} in FFI is highly experimental and \ may result in invalid code", diff --git a/compiler/rustc_typeck/src/collect/type_of.rs b/compiler/rustc_typeck/src/collect/type_of.rs index fd66bf949aaed..992bec316f751 100644 --- a/compiler/rustc_typeck/src/collect/type_of.rs +++ b/compiler/rustc_typeck/src/collect/type_of.rs @@ -267,7 +267,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { TraitItemKind::Const(ref ty, body_id) => body_id .and_then(|body_id| { if is_suggestable_infer_ty(ty) { - Some(infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident)) + let ty_span = tcx.hir().span(ty.hir_id); + Some(infer_placeholder_type(tcx, def_id, body_id, ty_span, item.ident)) } else { None } @@ -287,7 +288,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { } ImplItemKind::Const(ref ty, body_id) => { if is_suggestable_infer_ty(ty) { - infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident) + let ty_span = tcx.hir().span(ty.hir_id); + infer_placeholder_type(tcx, def_id, body_id, ty_span, item.ident) } else { icx.to_ty(ty) } @@ -306,7 +308,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { match item.kind { ItemKind::Static(ref ty, .., body_id) | ItemKind::Const(ref ty, body_id) => { if is_suggestable_infer_ty(ty) { - infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident) + let ty_span = tcx.hir().span(ty.hir_id); + infer_placeholder_type(tcx, def_id, body_id, ty_span, item.ident) } else { icx.to_ty(ty) } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index cd4f50b0f178b..064c62ebff4b6 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1282,7 +1282,8 @@ impl Clean for ty::AssocItem { fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type { use rustc_hir::GenericParamCount; - let hir::Ty { hir_id, span, ref kind } = *hir_ty; + let hir::Ty { hir_id, ref kind } = *hir_ty; + let span = cx.tcx.hir().span(hir_id); let qpath = match kind { hir::TyKind::Path(qpath) => qpath, _ => unreachable!(), diff --git a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs index 9462998e5f1a9..aa7f2f7dc0714 100644 --- a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs +++ b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs @@ -78,7 +78,7 @@ impl CognitiveComplexity { let fn_span = match kind { FnKind::ItemFn(ident, _, _, _) | FnKind::Method(ident, _, _) => ident.span, FnKind::Closure => { - let header_span = body_span.with_hi(decl.output.span().lo()); + let header_span = body_span.with_hi(decl.output.span(|id| cx.tcx.hir().span(id)).lo()); let pos = snippet_opt(cx, header_span).and_then(|snip| { let low_offset = snip.find('|')?; let high_offset = 1 + snip.get(low_offset + 1..)?.find('|')?; diff --git a/src/tools/clippy/clippy_lints/src/from_over_into.rs b/src/tools/clippy/clippy_lints/src/from_over_into.rs index c30554e67da67..07ef103f7df99 100644 --- a/src/tools/clippy/clippy_lints/src/from_over_into.rs +++ b/src/tools/clippy/clippy_lints/src/from_over_into.rs @@ -69,7 +69,7 @@ impl LateLintPass<'_> for FromOverInto { span_lint_and_help( cx, FROM_OVER_INTO, - cx.tcx.sess.source_map().guess_head_span(cx.tcx.hir().span(item.hir_id())), + cx.tcx.sess.source_map().guess_head_span(cx.tcx.hir().span_with_body(item.hir_id())), "an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true", None, "consider to implement `From` instead", diff --git a/src/tools/clippy/clippy_lints/src/functions.rs b/src/tools/clippy/clippy_lints/src/functions.rs index a1c2779a6e0f5..98cd421b5bfa8 100644 --- a/src/tools/clippy/clippy_lints/src/functions.rs +++ b/src/tools/clippy/clippy_lints/src/functions.rs @@ -269,9 +269,11 @@ impl<'tcx> LateLintPass<'tcx> for Functions { }, _, ) - | intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _) => { - self.check_arg_number(cx, decl, span.with_hi(decl.output.span().hi())) - }, + | intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _) => self.check_arg_number( + cx, + decl, + span.with_hi(decl.output.span(|id| cx.tcx.hir().span(id)).hi()), + ), _ => {}, } } @@ -286,7 +288,7 @@ impl<'tcx> LateLintPass<'tcx> for Functions { if let hir::ItemKind::Fn(ref sig, ref _generics, ref body_id) = item.kind { let is_public = cx.access_levels.is_exported(item.hir_id()); let item_span = cx.tcx.hir().span_with_body(item.hir_id()); - let fn_header_span = item_span.with_hi(sig.decl.output.span().hi()); + let fn_header_span = item_span.with_hi(sig.decl.output.span(|id| cx.tcx.hir().span(id)).hi()); if is_public { check_result_unit_err(cx, &sig.decl, item_span, fn_header_span); } @@ -301,7 +303,7 @@ impl<'tcx> LateLintPass<'tcx> for Functions { cx.tcx.hir().body(*body_id), item_span, item.hir_id(), - item_span.with_hi(sig.decl.output.span().hi()), + item_span.with_hi(sig.decl.output.span(|id| cx.tcx.hir().span(id)).hi()), "this function could have a `#[must_use]` attribute", ); } @@ -312,7 +314,7 @@ impl<'tcx> LateLintPass<'tcx> for Functions { if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind { let is_public = cx.access_levels.is_exported(item.hir_id()); let item_span = cx.tcx.hir().span_with_body(item.hir_id()); - let fn_header_span = item_span.with_hi(sig.decl.output.span().hi()); + let fn_header_span = item_span.with_hi(sig.decl.output.span(|id| cx.tcx.hir().span(id)).hi()); if is_public && trait_ref_of_method(cx, item.hir_id()).is_none() { check_result_unit_err(cx, &sig.decl, item_span, fn_header_span); } @@ -335,7 +337,7 @@ impl<'tcx> LateLintPass<'tcx> for Functions { cx.tcx.hir().body(*body_id), item_span, item.hir_id(), - item_span.with_hi(sig.decl.output.span().hi()), + item_span.with_hi(sig.decl.output.span(|id| cx.tcx.hir().span(id)).hi()), "this method could have a `#[must_use]` attribute", ); } @@ -348,10 +350,14 @@ impl<'tcx> LateLintPass<'tcx> for Functions { // don't lint extern functions decls, it's not their fault if sig.header.abi == Abi::Rust { - self.check_arg_number(cx, &sig.decl, item_span.with_hi(sig.decl.output.span().hi())); + self.check_arg_number( + cx, + &sig.decl, + item_span.with_hi(sig.decl.output.span(|id| cx.tcx.hir().span(id)).hi()), + ); } let is_public = cx.access_levels.is_exported(item.hir_id()); - let fn_header_span = item_span.with_hi(sig.decl.output.span().hi()); + let fn_header_span = item_span.with_hi(sig.decl.output.span(|id| cx.tcx.hir().span(id)).hi()); if is_public { check_result_unit_err(cx, &sig.decl, item_span, fn_header_span); } @@ -372,7 +378,7 @@ impl<'tcx> LateLintPass<'tcx> for Functions { body, item_span, item.hir_id(), - item_span.with_hi(sig.decl.output.span().hi()), + item_span.with_hi(sig.decl.output.span(|id| cx.tcx.hir().span(id)).hi()), "this method could have a `#[must_use]` attribute", ); } 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 afd5177a0ea2e..eec0de2696fe6 100644 --- a/src/tools/clippy/clippy_lints/src/future_not_send.rs +++ b/src/tools/clippy/clippy_lints/src/future_not_send.rs @@ -75,7 +75,7 @@ impl<'tcx> LateLintPass<'tcx> for FutureNotSend { } if is_future { let send_trait = cx.tcx.get_diagnostic_item(sym::send_trait).unwrap(); - let span = decl.output.span(); + let span = decl.output.span(|id| cx.tcx.hir().span(id)); let send_result = cx.tcx.infer_ctxt().enter(|infcx| { let cause = traits::ObligationCause::misc(span, hir_id); let mut fulfillment_cx = traits::FulfillmentContext::new(); 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 8d0d329319854..5c8c31edda479 100644 --- a/src/tools/clippy/clippy_lints/src/large_enum_variant.rs +++ b/src/tools/clippy/clippy_lints/src/large_enum_variant.rs @@ -59,7 +59,7 @@ impl_lint_pass!(LargeEnumVariant => [LARGE_ENUM_VARIANT]); impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { - if in_external_macro(cx.tcx.sess, cx.tcx.hir().span(item.hir_id())) { + if in_external_macro(cx.tcx.sess, cx.tcx.hir().span_with_body(item.hir_id())) { return; } if let ItemKind::Enum(ref def, _) = item.kind { @@ -113,7 +113,7 @@ impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { if variant.fields.len() == 1 { let span = match def.variants[i].data { VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => { - fields[0].ty.span + cx.tcx.hir().span(fields[0].ty.hir_id) }, VariantData::Unit(..) => unreachable!(), }; diff --git a/src/tools/clippy/clippy_lints/src/lifetimes.rs b/src/tools/clippy/clippy_lints/src/lifetimes.rs index a259e299c02d4..77c91d8b9ae92 100644 --- a/src/tools/clippy/clippy_lints/src/lifetimes.rs +++ b/src/tools/clippy/clippy_lints/src/lifetimes.rs @@ -180,7 +180,7 @@ fn check_fn_inner<'tcx>( span_lint( cx, NEEDLESS_LIFETIMES, - span.with_hi(decl.output.span().hi()), + span.with_hi(decl.output.span(|id| cx.tcx.hir().span(id)).hi()), "explicit lifetimes given in parameter types where they could be elided \ (or replaced with `'_` if needed by type declaration)", ); diff --git a/src/tools/clippy/clippy_lints/src/macro_use.rs b/src/tools/clippy/clippy_lints/src/macro_use.rs index a1f91587a5b43..92d96560a1e01 100644 --- a/src/tools/clippy/clippy_lints/src/macro_use.rs +++ b/src/tools/clippy/clippy_lints/src/macro_use.rs @@ -151,8 +151,9 @@ impl<'tcx> LateLintPass<'tcx> for MacroUseImports { } } fn check_ty(&mut self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) { - if in_macro(ty.span) { - self.push_unique_macro_pat_ty(cx, ty.span); + let ty_span = cx.tcx.hir().span(ty.hir_id); + if in_macro(ty_span) { + self.push_unique_macro_pat_ty(cx, ty_span); } } #[allow(clippy::too_many_lines)] 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 c04b4efaf7857..7eef59cd15b04 100644 --- a/src/tools/clippy/clippy_lints/src/manual_async_fn.rs +++ b/src/tools/clippy/clippy_lints/src/manual_async_fn.rs @@ -59,7 +59,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualAsyncFn { 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()); + let header_span = span.with_hi(cx.tcx.hir().span(ret_ty.hir_id).hi()); span_lint_and_then( cx, @@ -195,7 +195,7 @@ fn suggested_ret(cx: &LateContext<'_>, output: &Ty<'_>) -> Option<(&'static str, }, _ => { let sugg = "return the output of the future directly"; - snippet_opt(cx, output.span).map(|snip| (sugg, format!(" -> {}", snip))) + snippet_opt(cx, cx.tcx.hir().span(output.hir_id)).map(|snip| (sugg, format!(" -> {}", snip))) }, } } diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index fdc8f76630851..a24972d772313 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -1935,7 +1935,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { if_chain! { if let TraitItemKind::Fn(ref sig, _) = item.kind; if let Some(first_arg_ty) = sig.decl.inputs.iter().next(); - let first_arg_span = first_arg_ty.span; + let first_arg_span = cx.tcx.hir().span(first_arg_ty.hir_id); let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty); let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty(); diff --git a/src/tools/clippy/clippy_lints/src/misc.rs b/src/tools/clippy/clippy_lints/src/misc.rs index bd0f550718c34..40a534af2fe12 100644 --- a/src/tools/clippy/clippy_lints/src/misc.rs +++ b/src/tools/clippy/clippy_lints/src/misc.rs @@ -323,7 +323,8 @@ impl<'tcx> LateLintPass<'tcx> for MiscLints { ("", sugg_init.addr()) }; let tyopt = if let Some(ref ty) = local.ty { - format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "..")) + let ty_span = cx.tcx.hir().span(ty.hir_id); + format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty_span, "..")) } else { String::new() }; @@ -694,7 +695,7 @@ fn check_cast(cx: &LateContext<'_>, span: Span, e: &Expr<'_>, ty: &hir::Ty<'_>) let (sugg, appl) = if let TyKind::Infer = mut_ty.ty.kind { (format!("{}()", sugg_fn), Applicability::MachineApplicable) - } else if let Some(mut_ty_snip) = snippet_opt(cx, mut_ty.ty.span) { + } else if let Some(mut_ty_snip) = snippet_opt(cx, cx.tcx.hir().span(mut_ty.ty.hir_id)) { (format!("{}::<{}>()", sugg_fn, mut_ty_snip), Applicability::MachineApplicable) } else { // `MaybeIncorrect` as type inference may not work with the suggested code diff --git a/src/tools/clippy/clippy_lints/src/mut_key.rs b/src/tools/clippy/clippy_lints/src/mut_key.rs index 255e293676fe5..ce6d00a8564ef 100644 --- a/src/tools/clippy/clippy_lints/src/mut_key.rs +++ b/src/tools/clippy/clippy_lints/src/mut_key.rs @@ -88,9 +88,13 @@ fn check_sig<'tcx>(cx: &LateContext<'tcx>, item_hir_id: hir::HirId, decl: &hir:: let fn_def_id = cx.tcx.hir().local_def_id(item_hir_id); let fn_sig = cx.tcx.fn_sig(fn_def_id); for (hir_ty, ty) in decl.inputs.iter().zip(fn_sig.inputs().skip_binder().iter()) { - check_ty(cx, hir_ty.span, ty); + check_ty(cx, cx.tcx.hir().span(hir_ty.hir_id), ty); } - check_ty(cx, decl.output.span(), cx.tcx.erase_late_bound_regions(fn_sig.output())); + check_ty( + cx, + decl.output.span(|id| cx.tcx.hir().span(id)), + cx.tcx.erase_late_bound_regions(fn_sig.output()), + ); } // We want to lint 1. sets or maps with 2. not immutable key types and 3. no unerased diff --git a/src/tools/clippy/clippy_lints/src/mut_mut.rs b/src/tools/clippy/clippy_lints/src/mut_mut.rs index 23b4f1a1bb866..196e67209f4a2 100644 --- a/src/tools/clippy/clippy_lints/src/mut_mut.rs +++ b/src/tools/clippy/clippy_lints/src/mut_mut.rs @@ -100,7 +100,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> { span_lint( self.cx, MUT_MUT, - ty.span, + self.cx.tcx.hir().span(ty.hir_id), "generally you want to avoid `&mut &mut _` if possible", ); } 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 621e1224b028a..312df981c2962 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 @@ -144,7 +144,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { for (idx, ((input, &ty), arg)) in decl.inputs.iter().zip(fn_sig.inputs()).zip(body.params).enumerate() { // All spans generated from a proc-macro invocation are the same... - if span == input.span { + if span == cx.tcx.hir().span(input.hir_id) { return; } @@ -215,9 +215,9 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { _ => None, }).unwrap()); then { - let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_")); + let slice_ty = format!("&[{}]", snippet(cx, cx.tcx.hir().span(elem_ty.hir_id), "_")); diag.span_suggestion( - input.span, + cx.tcx.hir().span(input.hir_id), "consider changing the type to", slice_ty, Applicability::Unspecified, @@ -246,7 +246,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { if let Some(clone_spans) = get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) { diag.span_suggestion( - input.span, + cx.tcx.hir().span(input.hir_id), "consider changing the type to", "&str".to_string(), Applicability::Unspecified, @@ -270,7 +270,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { } } - let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))]; + let mut spans = vec![(cx.tcx.hir().span(input.hir_id), format!("&{}", snippet(cx, cx.tcx.hir().span(input.hir_id), "_")))]; // Suggests adding `*` to dereference the added reference. if let Some(deref_span) = deref_span { @@ -288,7 +288,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { span_lint_and_then( cx, NEEDLESS_PASS_BY_VALUE, - input.span, + cx.tcx.hir().span(input.hir_id), "this argument is passed by value, but not consumed in the function body", sugg, ); 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 5d28618466e4f..162273b570d17 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 @@ -122,7 +122,7 @@ impl<'tcx> PassByRefOrValue { for (index, (input, &ty)) in decl.inputs.iter().zip(fn_sig.inputs()).enumerate() { // All spans generated from a proc-macro invocation are the same... match span { - Some(s) if s == input.span => return, + Some(s) if s == cx.tcx.hir().span(input.hir_id) => return, _ => (), } @@ -147,12 +147,14 @@ impl<'tcx> PassByRefOrValue { let value_type = if is_self_ty(decl_ty) { "self".into() } else { - snippet(cx, decl_ty.span, "_").into() + let decl_ty_span = cx.tcx.hir().span(decl_ty.hir_id); + snippet(cx, decl_ty_span, "_").into() }; + let input_span = cx.tcx.hir().span(input.hir_id); span_lint_and_sugg( cx, TRIVIALLY_COPY_PASS_BY_REF, - input.span, + input_span, &format!("this argument ({} byte) is passed by reference, but would be more efficient if passed by value (limit: {} byte)", size, self.ref_min_size), "consider passing by value instead", value_type, @@ -178,13 +180,14 @@ impl<'tcx> PassByRefOrValue { if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes()); if size > self.value_max_size; then { + let input_span = cx.tcx.hir().span(input.hir_id); span_lint_and_sugg( cx, LARGE_TYPES_PASSED_BY_VALUE, - input.span, + input_span, &format!("this argument ({} byte) is passed by value, but might be more efficient if passed by reference (limit: {} byte)", size, self.value_max_size), "consider passing by reference instead", - format!("&{}", snippet(cx, input.span, "_")), + format!("&{}", snippet(cx, input_span, "_")), Applicability::MaybeIncorrect, ); } diff --git a/src/tools/clippy/clippy_lints/src/ptr.rs b/src/tools/clippy/clippy_lints/src/ptr.rs index 6ea2d8b06d81c..51897fad69b23 100644 --- a/src/tools/clippy/clippy_lints/src/ptr.rs +++ b/src/tools/clippy/clippy_lints/src/ptr.rs @@ -186,13 +186,13 @@ fn check_fn(cx: &LateContext<'_>, decl: &FnDecl<'_>, fn_id: HirId, opt_body_id: span_lint_and_then( cx, PTR_ARG, - arg.span, + cx.tcx.hir().span(arg.hir_id), "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \ with non-Vec-based slices", |diag| { if let Some(ref snippet) = get_only_generic_arg_snippet(cx, arg) { diag.span_suggestion( - arg.span, + cx.tcx.hir().span(arg.hir_id), "change this to", format!("&[{}]", snippet), Applicability::Unspecified, @@ -216,10 +216,15 @@ fn check_fn(cx: &LateContext<'_>, decl: &FnDecl<'_>, fn_id: HirId, opt_body_id: span_lint_and_then( cx, PTR_ARG, - arg.span, + cx.tcx.hir().span(arg.hir_id), "writing `&String` instead of `&str` involves a new object where a slice will do", |diag| { - diag.span_suggestion(arg.span, "change this to", "&str".into(), Applicability::Unspecified); + diag.span_suggestion( + cx.tcx.hir().span(arg.hir_id), + "change this to", + "&str".into(), + Applicability::Unspecified, + ); for (clonespan, suggestion) in spans { diag.span_suggestion_short( clonespan, @@ -238,11 +243,11 @@ fn check_fn(cx: &LateContext<'_>, decl: &FnDecl<'_>, fn_id: HirId, opt_body_id: span_lint_and_then( cx, PTR_ARG, - arg.span, + cx.tcx.hir().span(arg.hir_id), "writing `&PathBuf` instead of `&Path` involves a new object where a slice will do", |diag| { diag.span_suggestion( - arg.span, + cx.tcx.hir().span(arg.hir_id), "change this to", "&Path".into(), Applicability::Unspecified, @@ -272,12 +277,12 @@ fn check_fn(cx: &LateContext<'_>, decl: &FnDecl<'_>, fn_id: HirId, opt_body_id: _ => None, }); then { - let replacement = snippet_opt(cx, inner.span); + let replacement = snippet_opt(cx, cx.tcx.hir().span(inner.hir_id)); if let Some(r) = replacement { span_lint_and_sugg( cx, PTR_ARG, - arg.span, + cx.tcx.hir().span(arg.hir_id), "using a reference to `Cow` is not recommended", "change this to", "&".to_owned() + &r, @@ -291,12 +296,12 @@ fn check_fn(cx: &LateContext<'_>, decl: &FnDecl<'_>, fn_id: HirId, opt_body_id: } if let FnRetTy::Return(ref ty) = decl.output { - if let Some((out, Mutability::Mut, _)) = get_rptr_lm(ty) { + if let Some((out, Mutability::Mut, _)) = get_rptr_lm(cx, ty) { let mut immutables = vec![]; for (_, ref mutbl, ref argspan) in decl .inputs .iter() - .filter_map(|ty| get_rptr_lm(ty)) + .filter_map(|ty| get_rptr_lm(cx, ty)) .filter(|&(lt, _, _)| lt.name == out.name) { if *mutbl == Mutability::Mut { @@ -310,7 +315,7 @@ fn check_fn(cx: &LateContext<'_>, decl: &FnDecl<'_>, fn_id: HirId, opt_body_id: span_lint_and_then( cx, MUT_FROM_REF, - ty.span, + cx.tcx.hir().span(ty.hir_id), "mutable borrow from immutable input(s)", |diag| { let ms = MultiSpan::from_spans(immutables); @@ -331,16 +336,16 @@ fn get_only_generic_arg_snippet(cx: &LateContext<'_>, arg: &Ty<'_>) -> Option(ty: &'tcx Ty<'tcx>) -> Option<(&'tcx Lifetime, Mutability, Span)> { +fn get_rptr_lm<'tcx>(cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) -> Option<(&'tcx Lifetime, Mutability, Span)> { if let TyKind::Rptr(ref lt, ref m) = ty.kind { - Some((lt, m.mutbl, ty.span)) + Some((lt, m.mutbl, cx.tcx.hir().span(ty.hir_id))) } else { None } diff --git a/src/tools/clippy/clippy_lints/src/ref_option_ref.rs b/src/tools/clippy/clippy_lints/src/ref_option_ref.rs index 8cd6692ce03a0..2c2374344d141 100644 --- a/src/tools/clippy/clippy_lints/src/ref_option_ref.rs +++ b/src/tools/clippy/clippy_lints/src/ref_option_ref.rs @@ -52,13 +52,15 @@ impl<'tcx> LateLintPass<'tcx> for RefOptionRef { if let TyKind::Rptr(_, _) = inner_ty.kind; then { + let ty_span = cx.tcx.hir().span(ty.hir_id); + let inner_ty_span = cx.tcx.hir().span(inner_ty.hir_id); span_lint_and_sugg( cx, REF_OPTION_REF, - ty.span, + ty_span, "since `&` implements the `Copy` trait, `&Option<&T>` can be simplified to `Option<&T>`", "try", - format!("Option<{}>", &snippet(cx, inner_ty.span, "..")), + format!("Option<{}>", &snippet(cx, inner_ty_span, "..")), Applicability::MaybeIncorrect, ); } diff --git a/src/tools/clippy/clippy_lints/src/trait_bounds.rs b/src/tools/clippy/clippy_lints/src/trait_bounds.rs index daff5f81e8c34..c3a5442cdef1b 100644 --- a/src/tools/clippy/clippy_lints/src/trait_bounds.rs +++ b/src/tools/clippy/clippy_lints/src/trait_bounds.rs @@ -111,7 +111,7 @@ impl TraitBounds { then { let mut hint_string = format!( "consider combining the bounds: `{}:", - snippet(cx, p.bounded_ty.span, "_") + snippet(cx, cx.tcx.hir().span(p.bounded_ty.hir_id), "_") ); for b in v.iter() { if let GenericBound::Trait(ref poly_trait_ref, _) = b { diff --git a/src/tools/clippy/clippy_lints/src/transmute/utils.rs b/src/tools/clippy/clippy_lints/src/transmute/utils.rs index 55008d8ec3f16..f5538a724536f 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/utils.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/utils.rs @@ -22,7 +22,7 @@ pub(super) fn get_type_snippet(cx: &LateContext<'_>, path: &QPath<'_>, to_ref_ty }).nth(1); if let TyKind::Rptr(_, ref to_ty) = to_ty.kind; then { - return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string(); + return snippet(cx, cx.tcx.hir().span(to_ty.ty.hir_id), &to_ref_ty.to_string()).to_string(); } } diff --git a/src/tools/clippy/clippy_lints/src/types/borrowed_box.rs b/src/tools/clippy/clippy_lints/src/types/borrowed_box.rs index a7a511b21cf59..46dc8eddaab08 100644 --- a/src/tools/clippy/clippy_lints/src/types/borrowed_box.rs +++ b/src/tools/clippy/clippy_lints/src/types/borrowed_box.rs @@ -48,7 +48,7 @@ pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, lt: &Lifetime, m // When trait objects or opaque types have lifetime or auto-trait bounds, // we need to add parentheses to avoid a syntax error due to its ambiguity. // Originally reported as the issue #3128. - let inner_snippet = snippet(cx, inner.span, ".."); + let inner_snippet = snippet(cx, cx.tcx.hir().span(inner.hir_id), ".."); let suggestion = match &inner.kind { TyKind::TraitObject(bounds, lt_bound) if bounds.len() > 1 || !lt_bound.is_elided() => { format!("&{}({})", ltopt, &inner_snippet) @@ -64,7 +64,7 @@ pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, lt: &Lifetime, m span_lint_and_sugg( cx, BORROWED_BOX, - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), "you seem to be trying to use `&Box`. Consider using just `&T`", "try", suggestion, diff --git a/src/tools/clippy/clippy_lints/src/types/box_vec.rs b/src/tools/clippy/clippy_lints/src/types/box_vec.rs index 6aa98e435e160..a87a74274e5af 100644 --- a/src/tools/clippy/clippy_lints/src/types/box_vec.rs +++ b/src/tools/clippy/clippy_lints/src/types/box_vec.rs @@ -13,7 +13,7 @@ pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_ span_lint_and_help( cx, BOX_VEC, - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), "you seem to be trying to use `Box>`. Consider using just `Vec`", None, "`Vec` is already on the heap, `Box>` makes an extra allocation", diff --git a/src/tools/clippy/clippy_lints/src/types/linked_list.rs b/src/tools/clippy/clippy_lints/src/types/linked_list.rs index 47eb4ede4e422..d2ff79f0ab7ff 100644 --- a/src/tools/clippy/clippy_lints/src/types/linked_list.rs +++ b/src/tools/clippy/clippy_lints/src/types/linked_list.rs @@ -10,7 +10,7 @@ pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, def_id: DefId) - span_lint_and_help( cx, LINKEDLIST, - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), "you seem to be using a `LinkedList`! Perhaps you meant some other data structure?", None, "a `VecDeque` might work", diff --git a/src/tools/clippy/clippy_lints/src/types/mod.rs b/src/tools/clippy/clippy_lints/src/types/mod.rs index cd63560b05893..0607b56dcdcfa 100644 --- a/src/tools/clippy/clippy_lints/src/types/mod.rs +++ b/src/tools/clippy/clippy_lints/src/types/mod.rs @@ -310,7 +310,8 @@ impl Types { /// /// The parameter `is_local` distinguishes the context of the type. fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, is_local: bool) { - if hir_ty.span.from_expansion() { + let hir_ty_span = cx.tcx.hir().span(hir_ty.hir_id); + if hir_ty_span.from_expansion() { return; } match hir_ty.kind { @@ -869,7 +870,7 @@ impl<'tcx> TypeComplexity { } fn check_type(&self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) { - if ty.span.from_expansion() { + if cx.tcx.hir().span(ty.hir_id).from_expansion() { return; } let score = { @@ -882,7 +883,7 @@ impl<'tcx> TypeComplexity { span_lint( cx, TYPE_COMPLEXITY, - ty.span, + cx.tcx.hir().span(ty.hir_id), "very complex type used. Consider factoring parts into `type` definitions", ); } @@ -1520,16 +1521,16 @@ impl<'tcx> ImplicitHasherType<'tcx> { if is_type_diagnostic_item(cx, ty, sym::hashmap_type) && params_len == 2 { Some(ImplicitHasherType::HashMap( - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), ty, - snippet(cx, params[0].span, "K"), - snippet(cx, params[1].span, "V"), + snippet(cx, cx.tcx.hir().span(params[0].hir_id), "K"), + snippet(cx, cx.tcx.hir().span(params[1].hir_id), "V"), )) } else if is_type_diagnostic_item(cx, ty, sym::hashset_type) && params_len == 1 { Some(ImplicitHasherType::HashSet( - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), ty, - snippet(cx, params[0].span, "T"), + snippet(cx, cx.tcx.hir().span(params[0].hir_id), "T"), )) } else { None diff --git a/src/tools/clippy/clippy_lints/src/types/option_option.rs b/src/tools/clippy/clippy_lints/src/types/option_option.rs index dc5db963b4e98..21b0ed67b6bde 100644 --- a/src/tools/clippy/clippy_lints/src/types/option_option.rs +++ b/src/tools/clippy/clippy_lints/src/types/option_option.rs @@ -13,7 +13,7 @@ pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_ span_lint( cx, OPTION_OPTION, - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), "consider using `Option` instead of `Option>` or a custom \ enum if you need to distinguish all 3 cases", ); diff --git a/src/tools/clippy/clippy_lints/src/types/rc_buffer.rs b/src/tools/clippy/clippy_lints/src/types/rc_buffer.rs index e34b95147e10a..bb0c1389a3c3f 100644 --- a/src/tools/clippy/clippy_lints/src/types/rc_buffer.rs +++ b/src/tools/clippy/clippy_lints/src/types/rc_buffer.rs @@ -15,7 +15,7 @@ pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_ span_lint_and_sugg( cx, RC_BUFFER, - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), "usage of `Rc` when T is a buffer type", "try", format!("Rc<{}>", alternate), @@ -27,14 +27,14 @@ pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_ _ => return false, }; let inner_span = match get_qpath_generic_tys(qpath).next() { - Some(ty) => ty.span, + Some(ty) => cx.tcx.hir().span(ty.hir_id), None => return false, }; let mut applicability = Applicability::MachineApplicable; span_lint_and_sugg( cx, RC_BUFFER, - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), "usage of `Rc` when T is a buffer type", "try", format!( @@ -50,7 +50,7 @@ pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_ span_lint_and_sugg( cx, RC_BUFFER, - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), "usage of `Arc` when T is a buffer type", "try", format!("Arc<{}>", alternate), @@ -62,14 +62,14 @@ pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_ _ => return false, }; let inner_span = match get_qpath_generic_tys(qpath).next() { - Some(ty) => ty.span, + Some(ty) => cx.tcx.hir().span(ty.hir_id), None => return false, }; let mut applicability = Applicability::MachineApplicable; span_lint_and_sugg( cx, RC_BUFFER, - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), "usage of `Arc` when T is a buffer type", "try", format!( diff --git a/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs b/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs index 5da6db179c46e..db569a713581d 100644 --- a/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs +++ b/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs @@ -17,7 +17,7 @@ pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_ span_lint_and_sugg( cx, REDUNDANT_ALLOCATION, - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), "usage of `Box<&T>`", "try", snippet_with_applicability(cx, span, "..", &mut applicability).to_string(), @@ -33,10 +33,10 @@ pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_ span_lint_and_sugg( cx, REDUNDANT_ALLOCATION, - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), "usage of `Rc>`", "try", - snippet_with_applicability(cx, ty.span, "..", &mut applicability).to_string(), + snippet_with_applicability(cx, cx.tcx.hir().span(ty.hir_id), "..", &mut applicability).to_string(), applicability, ); true @@ -46,14 +46,14 @@ pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_ _ => return false, }; let inner_span = match get_qpath_generic_tys(qpath).next() { - Some(ty) => ty.span, + Some(ty) => cx.tcx.hir().span(ty.hir_id), None => return false, }; let mut applicability = Applicability::MachineApplicable; span_lint_and_sugg( cx, REDUNDANT_ALLOCATION, - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), "usage of `Rc>`", "try", format!( @@ -69,7 +69,7 @@ pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_ span_lint_and_sugg( cx, REDUNDANT_ALLOCATION, - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), "usage of `Rc<&T>`", "try", snippet_with_applicability(cx, span, "..", &mut applicability).to_string(), diff --git a/src/tools/clippy/clippy_lints/src/types/utils.rs b/src/tools/clippy/clippy_lints/src/types/utils.rs index 4d64748f998a4..bd863debb6570 100644 --- a/src/tools/clippy/clippy_lints/src/types/utils.rs +++ b/src/tools/clippy/clippy_lints/src/types/utils.rs @@ -6,7 +6,7 @@ use crate::utils::last_path_segment; use if_chain::if_chain; -pub(super) fn match_borrows_parameter(_cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option { +pub(super) fn match_borrows_parameter(cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option { let last = last_path_segment(qpath); if_chain! { if let Some(ref params) = last.args; @@ -17,7 +17,7 @@ pub(super) fn match_borrows_parameter(_cx: &LateContext<'_>, qpath: &QPath<'_>) }); if let TyKind::Rptr(..) = ty.kind; then { - return Some(ty.span); + return Some(cx.tcx.hir().span(ty.hir_id)); } } None diff --git a/src/tools/clippy/clippy_lints/src/types/vec_box.rs b/src/tools/clippy/clippy_lints/src/types/vec_box.rs index 2530cc133c678..af394cc209915 100644 --- a/src/tools/clippy/clippy_lints/src/types/vec_box.rs +++ b/src/tools/clippy/clippy_lints/src/types/vec_box.rs @@ -40,17 +40,17 @@ pub(super) fn check( }); let ty_ty = hir_ty_to_ty(cx.tcx, boxed_ty); if !ty_ty.has_escaping_bound_vars(); - if ty_ty.is_sized(cx.tcx.at(ty.span), cx.param_env); + if ty_ty.is_sized(cx.tcx.at(cx.tcx.hir().span(ty.hir_id)), cx.param_env); if let Ok(ty_ty_size) = cx.layout_of(ty_ty).map(|l| l.size.bytes()); if ty_ty_size <= box_size_threshold; then { span_lint_and_sugg( cx, VEC_BOX, - hir_ty.span, + cx.tcx.hir().span(hir_ty.hir_id), "`Vec` is already on the heap, the boxing is unnecessary", "try", - format!("Vec<{}>", snippet(cx, boxed_ty.span, "..")), + format!("Vec<{}>", snippet(cx, cx.tcx.hir().span(boxed_ty.hir_id), "..")), Applicability::MachineApplicable, ); true diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs index 121dc66963431..82efb0bf0125f 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs @@ -133,7 +133,7 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryWraps { ( "this function's return value is unnecessary".to_string(), "remove the return type...".to_string(), - snippet(cx, fn_decl.output.span(), "..").to_string(), + snippet(cx, fn_decl.output.span(|id| cx.tcx.hir().span(id)), "..").to_string(), "...and then remove returned values", ) } else { @@ -151,7 +151,7 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryWraps { let span = cx.tcx.hir().span_with_body(hir_id); span_lint_and_then(cx, UNNECESSARY_WRAPS, span, lint_msg.as_str(), |diag| { diag.span_suggestion( - fn_decl.output.span(), + fn_decl.output.span(|id| cx.tcx.hir().span(id)), return_type_sugg_msg.as_str(), return_type_sugg, Applicability::MaybeIncorrect, diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index 8362313644fcf..d0269527bb3cc 100644 --- a/src/tools/clippy/clippy_lints/src/use_self.rs +++ b/src/tools/clippy/clippy_lints/src/use_self.rs @@ -235,7 +235,10 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { } fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) { - if in_macro(hir_ty.span) | in_impl(cx, hir_ty) | !meets_msrv(self.msrv.as_ref(), &USE_SELF_MSRV) { + if in_macro(cx.tcx.hir().span(hir_ty.hir_id)) + | in_impl(cx, hir_ty) + | !meets_msrv(self.msrv.as_ref(), &USE_SELF_MSRV) + { return; } @@ -270,8 +273,8 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { Some(Node::Expr(Expr { kind: ExprKind::Path(QPath::TypeRelative(_, segment)), .. - })) => span_lint_until_last_segment(cx, hir_ty.span, segment), - _ => span_lint(cx, hir_ty.span), + })) => span_lint_until_last_segment(cx, cx.tcx.hir().span(hir_ty.hir_id), segment), + _ => span_lint(cx, cx.tcx.hir().span(hir_ty.hir_id)), } } } diff --git a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs index 8ebb17927cbd2..8040faab01fcf 100644 --- a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs +++ b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs @@ -100,7 +100,7 @@ impl LateLintPass<'_> for VecInitThenPush { local_id: id, init: init_kind, lhs_is_local: true, - lhs_span: local.ty.map_or(local_pat_span, |t| local_pat_span.to(t.span)), + lhs_span: local.ty.map_or(local_pat_span, |t| local_pat_span.to(cx.tcx.hir().span_with_body(t.hir_id))), err_span: local_span, found: 0, }); diff --git a/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs b/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs index adf7077e650fd..d4f74c00f61c0 100644 --- a/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs +++ b/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs @@ -45,7 +45,8 @@ declare_lint_pass!(ZeroSizedMapValues => [ZERO_SIZED_MAP_VALUES]); impl LateLintPass<'_> for ZeroSizedMapValues { fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) { if_chain! { - if !hir_ty.span.from_expansion(); + let hir_ty_span = cx.tcx.hir().span(hir_ty.hir_id); + if !hir_ty_span.from_expansion(); if !in_trait_impl(cx, hir_ty.hir_id); let ty = ty_from_hir_ty(cx, hir_ty); if is_type_diagnostic_item(cx, ty, sym::hashmap_type) || match_type(cx, ty, &paths::BTREEMAP); @@ -56,7 +57,7 @@ impl LateLintPass<'_> for ZeroSizedMapValues { if let Ok(layout) = cx.layout_of(ty); if layout.is_zst(); then { - span_lint_and_help(cx, ZERO_SIZED_MAP_VALUES, hir_ty.span, "map with zero-sized value type", None, "consider using a set instead"); + span_lint_and_help(cx, ZERO_SIZED_MAP_VALUES, hir_ty_span, "map with zero-sized value type", None, "consider using a set instead"); } } } From e281f67378a1c32c5c265a258a28e6b2635af16a Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 3 May 2020 19:57:29 +0200 Subject: [PATCH 39/41] Remove Span from hir::Expr. --- compiler/rustc_ast_lowering/src/expr.rs | 51 +++-- compiler/rustc_ast_lowering/src/item.rs | 7 +- compiler/rustc_ast_lowering/src/lib.rs | 14 +- compiler/rustc_hir/src/hir.rs | 3 +- compiler/rustc_hir_pretty/src/lib.rs | 10 +- .../infer/error_reporting/need_type_info.rs | 29 ++- compiler/rustc_lint/src/builtin.rs | 11 +- compiler/rustc_lint/src/methods.rs | 15 +- compiler/rustc_lint/src/non_fmt_panic.rs | 20 +- compiler/rustc_lint/src/noop_method_call.rs | 4 +- compiler/rustc_lint/src/types.rs | 22 +- compiler/rustc_lint/src/unused.rs | 9 +- compiler/rustc_middle/src/ich/impls_hir.rs | 3 +- compiler/rustc_middle/src/ty/consts.rs | 5 +- .../diagnostics/mutability_errors.rs | 4 +- .../rustc_mir/src/transform/coverage/mod.rs | 2 +- compiler/rustc_mir/src/util/spanview.rs | 4 +- compiler/rustc_mir_build/src/build/block.rs | 4 +- .../rustc_mir_build/src/build/matches/mod.rs | 12 +- compiler/rustc_mir_build/src/thir/cx/expr.rs | 91 +++++--- .../src/thir/pattern/check_match.rs | 8 +- .../rustc_mir_build/src/thir/pattern/mod.rs | 13 +- compiler/rustc_passes/src/check_const.rs | 6 +- compiler/rustc_passes/src/dead.rs | 2 +- compiler/rustc_passes/src/intrinsicck.rs | 23 +- compiler/rustc_passes/src/liveness.rs | 78 ++++--- compiler/rustc_passes/src/loops.rs | 28 +-- compiler/rustc_passes/src/naked_functions.rs | 5 +- compiler/rustc_passes/src/region.rs | 10 +- compiler/rustc_privacy/src/lib.rs | 14 +- .../src/traits/error_reporting/suggestions.rs | 18 +- compiler/rustc_typeck/src/check/_match.rs | 47 ++-- compiler/rustc_typeck/src/check/callee.rs | 61 +++-- compiler/rustc_typeck/src/check/cast.rs | 25 ++- compiler/rustc_typeck/src/check/check.rs | 8 +- compiler/rustc_typeck/src/check/closure.rs | 4 +- compiler/rustc_typeck/src/check/coercion.rs | 18 +- compiler/rustc_typeck/src/check/demand.rs | 67 +++--- compiler/rustc_typeck/src/check/expr.rs | 212 +++++++++++------- .../rustc_typeck/src/check/fn_ctxt/_impl.rs | 8 +- .../rustc_typeck/src/check/fn_ctxt/checks.rs | 44 ++-- .../src/check/fn_ctxt/suggestions.rs | 40 ++-- .../src/check/generator_interior.rs | 18 +- .../rustc_typeck/src/check/method/confirm.rs | 11 +- compiler/rustc_typeck/src/check/method/mod.rs | 2 +- .../rustc_typeck/src/check/method/suggest.rs | 39 ++-- compiler/rustc_typeck/src/check/mod.rs | 11 +- compiler/rustc_typeck/src/check/op.rs | 77 ++++--- compiler/rustc_typeck/src/check/pat.rs | 3 +- compiler/rustc_typeck/src/check/place_op.rs | 26 ++- compiler/rustc_typeck/src/check/regionck.rs | 16 +- compiler/rustc_typeck/src/check/upvar.rs | 3 +- compiler/rustc_typeck/src/check/writeback.rs | 19 +- compiler/rustc_typeck/src/expr_use_visitor.rs | 5 +- .../rustc_typeck/src/mem_categorization.rs | 17 +- src/librustdoc/clean/utils.rs | 5 +- .../clippy/clippy_lints/src/approx_const.rs | 2 +- .../clippy/clippy_lints/src/arithmetic.rs | 32 +-- .../src/assertions_on_constants.rs | 12 +- .../clippy/clippy_lints/src/assign_ops.rs | 14 +- .../clippy_lints/src/async_yields_async.rs | 4 +- .../clippy_lints/src/atomic_ordering.rs | 10 +- .../clippy_lints/src/await_holding_invalid.rs | 2 +- src/tools/clippy/clippy_lints/src/bit_mask.rs | 8 +- .../src/blocks_in_if_conditions.rs | 23 +- src/tools/clippy/clippy_lints/src/booleans.rs | 26 +-- .../clippy/clippy_lints/src/bytecount.rs | 6 +- .../clippy_lints/src/casts/cast_lossless.rs | 4 +- .../src/casts/cast_possible_truncation.rs | 2 +- .../src/casts/cast_possible_wrap.rs | 2 +- .../src/casts/cast_precision_loss.rs | 2 +- .../src/casts/cast_ptr_alignment.rs | 2 +- .../clippy_lints/src/casts/cast_ref_to_mut.rs | 2 +- .../clippy_lints/src/casts/cast_sign_loss.rs | 4 +- .../clippy_lints/src/casts/char_lit_as_u8.rs | 6 +- .../src/casts/fn_to_numeric_cast.rs | 5 +- .../fn_to_numeric_cast_with_truncation.rs | 5 +- .../clippy/clippy_lints/src/casts/mod.rs | 7 +- .../clippy_lints/src/casts/ptr_as_ptr.rs | 4 +- .../src/casts/unnecessary_cast.rs | 8 +- .../clippy_lints/src/checked_conversions.rs | 8 +- .../clippy_lints/src/collapsible_match.rs | 4 +- .../clippy_lints/src/comparison_chain.rs | 4 +- src/tools/clippy/clippy_lints/src/copies.rs | 12 +- .../clippy/clippy_lints/src/create_dir.rs | 4 +- src/tools/clippy/clippy_lints/src/default.rs | 11 +- .../clippy/clippy_lints/src/dereference.rs | 4 +- .../clippy_lints/src/disallowed_method.rs | 2 +- src/tools/clippy/clippy_lints/src/doc.rs | 9 +- .../clippy_lints/src/double_comparison.rs | 6 +- .../clippy_lints/src/drop_forget_ref.rs | 8 +- .../clippy_lints/src/duration_subsec.rs | 4 +- src/tools/clippy/clippy_lints/src/entry.rs | 16 +- src/tools/clippy/clippy_lints/src/eq_op.rs | 40 ++-- .../clippy/clippy_lints/src/erasing_op.rs | 8 +- .../clippy/clippy_lints/src/eta_reduction.rs | 16 +- .../clippy_lints/src/eval_order_dependence.rs | 11 +- src/tools/clippy/clippy_lints/src/exit.rs | 2 +- .../clippy/clippy_lints/src/explicit_write.rs | 11 +- .../clippy_lints/src/fallible_impl_from.rs | 10 +- .../src/float_equality_without_abs.rs | 4 +- .../clippy/clippy_lints/src/float_literal.rs | 4 +- .../src/floating_point_arithmetic.rs | 26 +-- src/tools/clippy/clippy_lints/src/format.rs | 4 +- .../clippy_lints/src/from_str_radix_10.rs | 2 +- .../clippy/clippy_lints/src/functions.rs | 6 +- .../clippy_lints/src/get_last_with_len.rs | 4 +- .../clippy/clippy_lints/src/identity_op.rs | 19 +- .../clippy/clippy_lints/src/if_let_mutex.rs | 2 +- .../clippy_lints/src/if_let_some_result.rs | 7 +- .../clippy_lints/src/implicit_return.rs | 10 +- .../src/implicit_saturating_sub.rs | 4 +- .../src/inconsistent_struct_constructor.rs | 4 +- .../clippy_lints/src/indexing_slicing.rs | 9 +- .../clippy/clippy_lints/src/infinite_iter.rs | 2 +- .../clippy_lints/src/integer_division.rs | 2 +- .../clippy_lints/src/large_stack_arrays.rs | 4 +- src/tools/clippy/clippy_lints/src/len_zero.rs | 27 +-- .../clippy/clippy_lints/src/let_if_seq.rs | 8 +- .../clippy_lints/src/loops/empty_loop.rs | 2 +- .../src/loops/explicit_counter_loop.rs | 4 +- .../src/loops/explicit_into_iter_loop.rs | 4 +- .../src/loops/explicit_iter_loop.rs | 4 +- .../clippy_lints/src/loops/for_kv_map.rs | 4 +- .../src/loops/for_loops_over_fallibles.rs | 13 +- .../clippy_lints/src/loops/iter_next_loop.rs | 2 +- .../clippy_lints/src/loops/manual_flatten.rs | 4 +- .../clippy_lints/src/loops/manual_memcpy.rs | 6 +- .../clippy/clippy_lints/src/loops/mod.rs | 4 +- .../src/loops/needless_collect.rs | 31 +-- .../src/loops/needless_range_loop.rs | 17 +- .../clippy_lints/src/loops/never_loop.rs | 7 +- .../clippy_lints/src/loops/same_item_push.rs | 6 +- .../src/loops/single_element_loop.rs | 2 +- .../clippy/clippy_lints/src/loops/utils.rs | 4 +- .../src/loops/while_immutable_condition.rs | 2 +- .../clippy_lints/src/loops/while_let_loop.rs | 11 +- .../src/loops/while_let_on_iterator.rs | 8 +- .../clippy/clippy_lints/src/macro_use.rs | 5 +- .../clippy/clippy_lints/src/main_recursion.rs | 4 +- .../clippy_lints/src/manual_async_fn.rs | 2 +- .../clippy/clippy_lints/src/manual_map.rs | 30 +-- .../clippy/clippy_lints/src/manual_ok_or.rs | 10 +- .../clippy/clippy_lints/src/manual_strip.rs | 10 +- .../clippy_lints/src/manual_unwrap_or.rs | 14 +- .../clippy/clippy_lints/src/map_clone.rs | 10 +- .../clippy/clippy_lints/src/map_err_ignore.rs | 2 +- .../clippy/clippy_lints/src/map_identity.rs | 4 +- .../clippy/clippy_lints/src/map_unit_fn.rs | 22 +- .../clippy_lints/src/match_on_vec_items.rs | 8 +- src/tools/clippy/clippy_lints/src/matches.rs | 106 +++++---- .../clippy_lints/src/mem_discriminant.rs | 6 +- .../clippy/clippy_lints/src/mem_forget.rs | 2 +- .../clippy/clippy_lints/src/mem_replace.rs | 13 +- .../src/methods/bind_instead_of_map.rs | 24 +- .../clippy_lints/src/methods/bytes_nth.rs | 6 +- .../clippy_lints/src/methods/clone_on_copy.rs | 15 +- .../src/methods/clone_on_ref_ptr.rs | 4 +- .../src/methods/expect_fun_call.rs | 11 +- .../clippy_lints/src/methods/expect_used.rs | 2 +- .../src/methods/filetype_is_file.rs | 4 +- .../src/methods/filter_flat_map.rs | 2 +- .../clippy_lints/src/methods/filter_map.rs | 2 +- .../src/methods/filter_map_flat_map.rs | 2 +- .../src/methods/filter_map_identity.rs | 2 +- .../src/methods/filter_map_map.rs | 2 +- .../src/methods/filter_map_next.rs | 8 +- .../clippy_lints/src/methods/filter_next.rs | 8 +- .../src/methods/flat_map_identity.rs | 2 +- .../methods/from_iter_instead_of_collect.rs | 4 +- .../clippy_lints/src/methods/get_unwrap.rs | 8 +- .../src/methods/inefficient_to_string.rs | 6 +- .../src/methods/inspect_for_each.rs | 2 +- .../src/methods/iter_cloned_collect.rs | 2 +- .../clippy_lints/src/methods/iter_count.rs | 4 +- .../src/methods/iter_next_slice.rs | 8 +- .../clippy_lints/src/methods/iter_nth.rs | 2 +- .../clippy_lints/src/methods/iter_nth_zero.rs | 4 +- .../src/methods/iter_skip_next.rs | 8 +- .../src/methods/iterator_step_by_zero.rs | 2 +- .../methods/manual_saturating_arithmetic.rs | 12 +- .../src/methods/map_collect_result_unit.rs | 6 +- .../clippy_lints/src/methods/map_flatten.rs | 14 +- .../clippy_lints/src/methods/map_unwrap_or.rs | 12 +- .../clippy/clippy_lints/src/methods/mod.rs | 20 +- .../clippy_lints/src/methods/ok_expect.rs | 2 +- .../src/methods/option_as_ref_deref.rs | 18 +- .../src/methods/option_map_or_none.rs | 8 +- .../src/methods/option_map_unwrap_or.rs | 10 +- .../clippy_lints/src/methods/or_fun_call.rs | 40 +++- .../src/methods/search_is_some.rs | 10 +- .../src/methods/single_char_insert_string.rs | 12 +- .../src/methods/single_char_pattern.rs | 2 +- .../src/methods/single_char_push_string.rs | 10 +- .../src/methods/skip_while_next.rs | 2 +- .../src/methods/string_extend_chars.rs | 8 +- .../src/methods/suspicious_map.rs | 2 +- .../src/methods/uninit_assumed_init.rs | 2 +- .../src/methods/unnecessary_filter_map.rs | 4 +- .../src/methods/unnecessary_fold.rs | 4 +- .../src/methods/unnecessary_lazy_eval.rs | 6 +- .../clippy_lints/src/methods/unwrap_used.rs | 2 +- .../clippy_lints/src/methods/useless_asref.rs | 6 +- .../clippy_lints/src/methods/zst_offset.rs | 2 +- src/tools/clippy/clippy_lints/src/minmax.rs | 2 +- src/tools/clippy/clippy_lints/src/misc.rs | 59 +++-- .../clippy_lints/src/modulo_arithmetic.rs | 4 +- src/tools/clippy/clippy_lints/src/mut_mut.rs | 6 +- .../clippy/clippy_lints/src/mut_reference.rs | 2 +- .../src/mutable_debug_assertion.rs | 4 +- .../clippy/clippy_lints/src/mutex_atomic.rs | 7 +- .../clippy/clippy_lints/src/needless_bool.rs | 38 ++-- .../clippy_lints/src/needless_borrow.rs | 9 +- .../src/needless_question_mark.rs | 7 +- .../clippy_lints/src/needless_update.rs | 2 +- .../src/neg_cmp_op_on_partial_ord.rs | 4 +- .../clippy/clippy_lints/src/neg_multiply.rs | 4 +- .../clippy/clippy_lints/src/no_effect.rs | 8 +- .../clippy/clippy_lints/src/non_copy_const.rs | 2 +- .../clippy/clippy_lints/src/open_options.rs | 2 +- .../clippy_lints/src/option_if_let_else.rs | 8 +- .../src/overflow_check_conditional.rs | 8 +- .../clippy_lints/src/panic_in_result_fn.rs | 1 + .../clippy_lints/src/panic_unimplemented.rs | 20 +- src/tools/clippy/clippy_lints/src/ptr.rs | 2 +- src/tools/clippy/clippy_lints/src/ptr_eq.rs | 8 +- .../clippy_lints/src/ptr_offset_with_cast.rs | 8 +- .../clippy/clippy_lints/src/question_mark.rs | 8 +- src/tools/clippy/clippy_lints/src/ranges.rs | 32 +-- .../src/redundant_closure_call.rs | 2 +- .../clippy_lints/src/redundant_slicing.rs | 6 +- src/tools/clippy/clippy_lints/src/regex.rs | 16 +- .../clippy/clippy_lints/src/repeat_once.rs | 16 +- src/tools/clippy/clippy_lints/src/returns.rs | 27 ++- .../clippy_lints/src/self_assignment.rs | 6 +- .../src/semicolon_if_nothing_returned.rs | 4 +- src/tools/clippy/clippy_lints/src/shadow.rs | 18 +- .../src/size_of_in_element_count.rs | 2 +- .../src/slow_vector_initialization.rs | 4 +- .../clippy_lints/src/stable_sort_primitive.rs | 4 +- src/tools/clippy/clippy_lints/src/strings.rs | 30 +-- src/tools/clippy/clippy_lints/src/swap.rs | 10 +- .../clippy_lints/src/temporary_assignment.rs | 2 +- .../clippy_lints/src/to_digit_is_some.rs | 6 +- .../clippy_lints/src/to_string_in_display.rs | 2 +- .../src/transmute/crosspointer_transmute.rs | 4 +- .../src/transmute/transmute_float_to_int.rs | 9 +- .../src/transmute/transmute_int_to_bool.rs | 4 +- .../src/transmute/transmute_int_to_char.rs | 4 +- .../src/transmute/transmute_int_to_float.rs | 4 +- .../src/transmute/transmute_ptr_to_ptr.rs | 9 +- .../src/transmute/transmute_ptr_to_ref.rs | 4 +- .../src/transmute/transmute_ref_to_ref.rs | 8 +- .../transmutes_expressible_as_ptr_casts.rs | 9 +- .../transmute/unsound_collection_transmute.rs | 2 +- .../src/transmute/useless_transmute.rs | 15 +- .../src/transmute/wrong_transmute.rs | 2 +- .../clippy_lints/src/transmuting_null.rs | 8 +- src/tools/clippy/clippy_lints/src/try_err.rs | 20 +- .../clippy/clippy_lints/src/types/mod.rs | 78 ++++--- .../src/undropped_manually_drops.rs | 2 +- .../clippy_lints/src/unnamed_address.rs | 6 +- .../clippy_lints/src/unnecessary_sort_by.rs | 4 +- .../clippy_lints/src/unnecessary_wraps.rs | 6 +- .../clippy_lints/src/unused_io_amount.rs | 9 +- src/tools/clippy/clippy_lints/src/unwrap.rs | 14 +- .../clippy_lints/src/unwrap_in_result.rs | 8 +- .../clippy_lints/src/useless_conversion.rs | 20 +- .../clippy_lints/src/utils/internal_lints.rs | 43 ++-- src/tools/clippy/clippy_lints/src/vec.rs | 10 +- .../clippy_lints/src/vec_init_then_push.rs | 8 +- .../clippy_lints/src/vec_resize_to_zero.rs | 5 +- .../clippy_lints/src/verbose_file_reads.rs | 4 +- .../clippy/clippy_lints/src/zero_div_zero.rs | 2 +- src/tools/clippy/clippy_utils/src/consts.rs | 2 +- src/tools/clippy/clippy_utils/src/higher.rs | 2 +- .../clippy/clippy_utils/src/hir_utils.rs | 7 +- src/tools/clippy/clippy_utils/src/lib.rs | 39 ++-- src/tools/clippy/clippy_utils/src/ptr.rs | 2 +- src/tools/clippy/clippy_utils/src/sugg.rs | 6 +- src/tools/clippy/clippy_utils/src/usage.rs | 18 +- 281 files changed, 1946 insertions(+), 1443 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index c4bff914a0b97..8669d0ebe2f6f 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -252,11 +252,11 @@ impl<'hir> LoweringContext<'_, 'hir> { ExprKind::Err => hir::ExprKind::Err, ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr), ExprKind::Paren(ref ex) => { - let mut ex = self.lower_expr_mut(ex); + let ex = self.lower_expr_mut(ex); // 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; + let ex_span = &mut self.spans[ex.hir_id]; + if e.span.contains(*ex_span) { + *ex_span = e.span; } // Merge attributes into the inner expression. if !e.attrs.is_empty() { @@ -284,7 +284,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let hir_id = self.lower_node_id(e.id, e.span); self.lower_attrs(hir_id, &e.attrs); - hir::Expr { hir_id, kind, span: e.span } + hir::Expr { hir_id, kind } }) } @@ -535,8 +535,11 @@ impl<'hir> LoweringContext<'_, 'hir> { // Lower condition: let cond = self.with_loop_condition_scope(|this| this.lower_expr(cond)); - let span_block = - self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None); + let span_block = self.mark_span_with_reason( + DesugaringKind::CondTemporary, + self.spans[cond.hir_id], + None, + ); // Wrap in a construct equivalent to `{ let _t = $cond; _t }` // to preserve drop semantics since `while cond { ... }` does not // let temporaries live outside of `cond`. @@ -574,7 +577,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ( this.mark_span_with_reason( DesugaringKind::TryBlock, - expr.span, + this.spans[expr.hir_id], this.allow_try_trait.clone(), ), expr, @@ -589,8 +592,11 @@ impl<'hir> LoweringContext<'_, 'hir> { (try_span, this.expr_unit(try_span)) }; - let ok_wrapped_span = - this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None); + let ok_wrapped_span = this.mark_span_with_reason( + DesugaringKind::TryBlock, + this.spans[tail_expr.hir_id], + None, + ); // `::std::ops::Try::from_ok($tail_expr)` block.expr = Some(this.wrap_in_try_constructor( @@ -692,11 +698,8 @@ impl<'hir> LoweringContext<'_, 'hir> { span, Some(hir::Movability::Static), ); - let generator = hir::Expr { - hir_id: self.lower_node_id(closure_node_id, span), - kind: generator_kind, - span, - }; + let generator = + hir::Expr { hir_id: self.lower_node_id(closure_node_id, span), kind: generator_kind }; // `future::from_generator`: let unstable_span = @@ -849,7 +852,6 @@ impl<'hir> LoweringContext<'_, 'hir> { let loop_expr = self.arena.alloc(hir::Expr { hir_id: loop_hir_id, kind: hir::ExprKind::Loop(loop_block, None, hir::LoopSource::Loop, span), - span, }); // mut pinned => loop { ... } @@ -1720,13 +1722,12 @@ impl<'hir> LoweringContext<'_, 'hir> { ) -> hir::Expr<'hir> { let orig_head_span = head.span; // expand - let mut head = self.lower_expr_mut(head); + let head = self.lower_expr_mut(head); let desugared_span = self.mark_span_with_reason( DesugaringKind::ForLoop(ForLoopLoc::Head), orig_head_span, None, ); - head.span = desugared_span; self.spans[head.hir_id] = desugared_span; let iter = Ident::with_dummy_span(sym::iter); @@ -1818,11 +1819,8 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::LoopSource::ForLoop, e.span.with_hi(orig_head_span.hi()), ); - let loop_expr = self.arena.alloc(hir::Expr { - hir_id: self.lower_node_id(e.id, e.span), - kind, - span: e.span, - }); + let loop_expr = + self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id, e.span), kind }); // `mut iter => { ... }` let iter_arm = self.arm(iter_pat, loop_expr); @@ -2118,7 +2116,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> { - let span = expr.span; + let span = self.spans[expr.hir_id]; let hir_id = self.next_id(span); self.expr( span, @@ -2159,7 +2157,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ) -> hir::Expr<'hir> { let hir_id = self.next_id(span); self.lower_attrs(hir_id, &attrs); - hir::Expr { hir_id, kind, span } + hir::Expr { hir_id, kind } } fn field(&mut self, ident: Ident, expr: &'hir hir::Expr<'hir>, span: Span) -> hir::Field<'hir> { @@ -2167,6 +2165,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> { - hir::Arm { hir_id: self.next_id(expr.span), pat, guard: None, body: expr } + let span = self.spans[expr.hir_id]; + hir::Arm { hir_id: self.next_id(span), pat, guard: None, body: expr } } } diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index f88be91718fb8..87c42386d867d 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1238,8 +1238,11 @@ impl<'hir> LoweringContext<'_, 'hir> { let user_body = this.lower_block_expr_opt(body_span, body); // Transform into `drop-temps { }`, an expression: - let desugared_span = - this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None); + let desugared_span = this.mark_span_with_reason( + DesugaringKind::Async, + this.spans[user_body.hir_id], + None, + ); let user_body = this.expr_drop_temps( desugared_span, this.arena.alloc(user_body), diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 250379672fafb..e16f1fd0db53d 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -573,7 +573,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let module = self.lower_mod(&c.items, c.span); self.lower_attrs(hir::CRATE_HIR_ID, &c.attrs); - let body_ids = body_ids(&self.bodies); + let body_ids = body_ids(&self.bodies, &self.spans); let proc_macros = c.proc_macros.iter().map(|id| self.node_id_to_hir_id[*id].unwrap()).collect(); @@ -2454,7 +2454,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst { self.with_new_scopes(|this| { let body = this.lower_const_body(c.value.span, Some(&c.value)); - let span = this.bodies[&body].value.span; + let span = this.spans[this.bodies[&body].value.hir_id]; hir::AnonConst { hir_id: this.lower_node_id(c.id, span), body } }) } @@ -2569,7 +2569,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> { - self.block_all(expr.span, &[], Some(expr)) + let span = self.spans[expr.hir_id]; + self.block_all(span, &[], Some(expr)) } fn block_all( @@ -2868,11 +2869,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } } -fn body_ids(bodies: &BTreeMap>) -> Vec { +fn body_ids( + bodies: &BTreeMap>, + spans: &HirIdVec, +) -> Vec { // Sorting by span ensures that we get things in order within a // file, and also puts the files in a sensible order. let mut body_ids: Vec<_> = bodies.keys().cloned().collect(); - body_ids.sort_by_key(|b| bodies[b].value.span); + body_ids.sort_by_key(|b| spans[bodies[b].value.hir_id]); body_ids } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 979789a88f82a..218ce6cf9bc9c 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1423,7 +1423,6 @@ pub struct AnonConst { pub struct Expr<'hir> { pub hir_id: HirId, pub kind: ExprKind<'hir>, - pub span: Span, } impl Expr<'_> { @@ -3034,7 +3033,7 @@ impl<'hir> Node<'hir> { #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] mod size_asserts { rustc_data_structures::static_assert_size!(super::Block<'static>, 40); - rustc_data_structures::static_assert_size!(super::Expr<'static>, 64); + rustc_data_structures::static_assert_size!(super::Expr<'static>, 56); rustc_data_structures::static_assert_size!(super::Pat<'static>, 80); rustc_data_structures::static_assert_size!(super::QPath<'static>, 24); rustc_data_structures::static_assert_size!(super::Ty<'static>, 64); diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index b70a34d5b42b9..38abc64b3afda 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -363,7 +363,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), |s, e| s.span(e.hir_id)) } pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) { @@ -1122,7 +1122,7 @@ 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(span.hi())); + self.maybe_print_trailing_comment(self.span(expr.hir_id), Some(span.hi())); } self.bclose_maybe_open(span, close_box); self.ann.post(self, AnnNode::Block(blk)) @@ -1368,7 +1368,7 @@ impl<'a> State<'a> { } pub fn print_expr(&mut self, expr: &hir::Expr<'_>) { - self.maybe_print_comment(expr.span.lo()); + self.maybe_print_comment(self.span(expr.hir_id).lo()); self.print_outer_attributes(self.attrs(expr.hir_id)); self.ibox(INDENT_UNIT); self.ann.pre(self, AnnNode::Expr(expr)); @@ -1439,7 +1439,7 @@ impl<'a> State<'a> { self.print_ident(temp); // Print `}`: - self.bclose_maybe_open(expr.span, true); + self.bclose_maybe_open(self.span(expr.hir_id), true); } hir::ExprKind::If(ref test, ref blk, ref elseopt) => { self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e)); @@ -1463,7 +1463,7 @@ impl<'a> State<'a> { for arm in arms { self.print_arm(arm); } - self.bclose(expr.span); + self.bclose(self.span(expr.hir_id)); } hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => { self.print_capture_clause(capture_clause); 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 ec297fec01b57..5b11df8f90757 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 @@ -75,9 +75,9 @@ impl<'a, 'tcx> FindHirNodeVisitor<'a, 'tcx> { /// Determine whether the expression, assumed to be the callee within a `Call`, /// corresponds to the `From::from` emitted in desugaring of the `?` operator. fn is_try_conversion(&self, callee: &Expr<'tcx>) -> bool { - self.infcx - .trait_def_from_hir_fn(callee.hir_id) - .map_or(false, |def_id| self.infcx.is_try_conversion(callee.span, def_id)) + self.infcx.trait_def_from_hir_fn(callee.hir_id).map_or(false, |def_id| { + self.infcx.is_try_conversion(self.infcx.tcx.hir().span(callee.hir_id), def_id) + }) } } @@ -139,13 +139,16 @@ impl<'a, 'tcx> Visitor<'tcx> for FindHirNodeVisitor<'a, 'tcx> { // `From::from(e)` call emitted during desugaring of the `?` operator, // extract the types inferred before and after the call ExprKind::Call(callee, [arg]) - if self.target_span.contains(expr.span) + if self.target_span.contains(self.infcx.tcx.hir().span(expr.hir_id)) && self.found_use_diagnostic.is_none() && self.is_try_conversion(callee) => { - self.found_use_diagnostic = self.node_type_opt(arg.hir_id).map(|pre_ty| { - UseDiagnostic::TryConversion { pre_ty, post_ty: ty, span: callee.span } - }); + self.found_use_diagnostic = + self.node_type_opt(arg.hir_id).map(|pre_ty| UseDiagnostic::TryConversion { + pre_ty, + post_ty: ty, + span: self.infcx.tcx.hir().span(callee.hir_id), + }); } _ => {} } @@ -230,7 +233,7 @@ fn closure_return_type_suggestion( } _ => vec![ (output.span(|id| tcx.hir().span(id)), format!("{}{}{}{{ ", arrow, ret, post)), - (body.value.span.shrink_to_hi(), " }".to_string()), + (tcx.hir().span(body.value.hir_id).shrink_to_hi(), " }".to_string()), ], }; err.multipart_suggestion( @@ -673,7 +676,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { // | help: specify type like: `>::into(foo_impl)` // | // = note: cannot satisfy `Impl: Into<_>` - if !impl_candidates.is_empty() && e.span.contains(span) { + let e_span = self.tcx.hir().span(e.hir_id); + if !impl_candidates.is_empty() && e_span.contains(span) { if let Some(expr) = exprs.first() { if let ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind { if let [path_segment] = path.segments { @@ -685,7 +689,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { ) }); err.span_suggestions( - e.span, + e_span, &format!( "use the fully qualified path for the potential candidate{}", pluralize!(candidate_len), @@ -824,7 +828,10 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { let sig = self.tcx.fn_sig(did); let bound_output = sig.output(); let output = bound_output.skip_binder(); - err.span_label(e.span, &format!("this method call resolves to `{}`", output)); + err.span_label( + self.tcx.hir().span(e.hir_id), + &format!("this method call resolves to `{}`", output), + ); let kind = output.kind(); if let ty::Projection(proj) = kind { if let Some(span) = self.tcx.hir().span_if_local(proj.item_def_id) { diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 49ede4f25f61c..42757a8c956da 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -1198,7 +1198,9 @@ impl<'tcx> LateLintPass<'tcx> for MutableTransmutes { if to_mt == hir::Mutability::Mut && from_mt == hir::Mutability::Not { let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \ consider instead using an UnsafeCell"; - cx.struct_span_lint(MUTABLE_TRANSMUTES, expr.span, |lint| lint.build(msg).emit()); + cx.struct_span_lint(MUTABLE_TRANSMUTES, cx.tcx.hir().span(expr.hir_id), |lint| { + lint.build(msg).emit() + }); } } @@ -2555,7 +2557,8 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { if let Some((msg, span)) = with_no_trimmed_paths(|| ty_find_init_error(cx.tcx, conjured_ty, init)) { - cx.struct_span_lint(INVALID_VALUE, expr.span, |lint| { + let expr_span = cx.tcx.hir().span(expr.hir_id); + cx.struct_span_lint(INVALID_VALUE, expr_span, |lint| { let mut err = lint.build(&format!( "the type `{}` does not permit {}", conjured_ty, @@ -2564,9 +2567,9 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { InitKind::Uninit => "being left uninitialized", }, )); - err.span_label(expr.span, "this code causes undefined behavior when executed"); + err.span_label(expr_span, "this code causes undefined behavior when executed"); err.span_label( - expr.span, + expr_span, "help: use `MaybeUninit` instead, \ and only call `assume_init` after initialization is done", ); diff --git a/compiler/rustc_lint/src/methods.rs b/compiler/rustc_lint/src/methods.rs index 8732845af0cec..cb9e132761723 100644 --- a/compiler/rustc_lint/src/methods.rs +++ b/compiler/rustc_lint/src/methods.rs @@ -42,10 +42,15 @@ fn in_macro(span: Span) -> bool { } fn first_method_call<'tcx>( + cx: &LateContext<'_>, expr: &'tcx Expr<'tcx>, ) -> Option<(&'tcx PathSegment<'tcx>, &'tcx [Expr<'tcx>])> { if let ExprKind::MethodCall(path, _, args, _) = &expr.kind { - if args.iter().any(|e| e.span.from_expansion()) { None } else { Some((path, *args)) } + if args.iter().any(|e| cx.tcx.hir().span(e.hir_id).from_expansion()) { + None + } else { + Some((path, *args)) + } } else { None } @@ -53,15 +58,15 @@ fn first_method_call<'tcx>( impl<'tcx> LateLintPass<'tcx> for TemporaryCStringAsPtr { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if in_macro(expr.span) { + if in_macro(cx.tcx.hir().span(expr.hir_id)) { return; } - match first_method_call(expr) { + match first_method_call(cx, expr) { Some((path, args)) if path.ident.name == sym::as_ptr => { let unwrap_arg = &args[0]; let as_ptr_span = path.ident.span; - match first_method_call(unwrap_arg) { + match first_method_call(cx, unwrap_arg) { Some((path, args)) if path.ident.name == sym::unwrap || path.ident.name == sym::expect => { @@ -92,7 +97,7 @@ fn lint_cstring_as_ptr( .build("getting the inner pointer of a temporary `CString`"); diag.span_label(as_ptr_span, "this pointer will be invalid"); diag.span_label( - unwrap.span, + cx.tcx.hir().span(unwrap.hir_id), "this `CString` is deallocated at the end of the statement, bind it to a variable to extend its lifetime", ); diag.note("pointers do not have a lifetime; when calling `as_ptr` the `CString` will be deallocated at the end of the statement because nothing is referencing it as far as the type system is concerned"); diff --git a/compiler/rustc_lint/src/non_fmt_panic.rs b/compiler/rustc_lint/src/non_fmt_panic.rs index 5a27135581747..2305c8dad0286 100644 --- a/compiler/rustc_lint/src/non_fmt_panic.rs +++ b/compiler/rustc_lint/src/non_fmt_panic.rs @@ -43,7 +43,8 @@ impl<'tcx> LateLintPass<'tcx> for NonPanicFmt { || Some(def_id) == cx.tcx.lang_items().panic_fn() || Some(def_id) == cx.tcx.lang_items().panic_str() { - if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id { + let f_span = cx.tcx.hir().span(f.hir_id); + if let Some(id) = f_span.ctxt().outer_expn_data().macro_def_id { if cx.tcx.is_diagnostic_item(sym::std_panic_2015_macro, id) || cx.tcx.is_diagnostic_item(sym::core_panic_2015_macro, id) { @@ -74,7 +75,7 @@ fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tc // We don't use source_callsite(), because this `panic!(..)` might itself // be expanded from another macro, in which case we want to stop at that // expansion. - let mut arg_span = arg.span; + let mut arg_span = cx.tcx.hir().span(arg.hir_id); let mut arg_macro = None; while !span.contains(arg_span) { let expn = arg_span.ctxt().outer_expn_data(); @@ -145,7 +146,8 @@ fn check_panic_str<'tcx>( return; } - let fmt_span = arg.span.source_callsite(); + let arg_span = cx.tcx.hir().span(arg.hir_id); + let fmt_span = arg_span.source_callsite(); let (snippet, style) = match cx.sess().parse_sess.source_map().span_to_snippet(fmt_span) { Ok(snippet) => { @@ -173,15 +175,15 @@ fn check_panic_str<'tcx>( _ => "panic message contains unused formatting placeholders", }); l.note("this message is not used as a format string when given without arguments, but will be in Rust 2021"); - if span.contains(arg.span) { + if span.contains(arg_span) { l.span_suggestion( - arg.span.shrink_to_hi(), + arg_span.shrink_to_hi(), &format!("add the missing argument{}", pluralize!(n_arguments)), ", ...".into(), Applicability::HasPlaceholders, ); l.span_suggestion( - arg.span.shrink_to_lo(), + arg_span.shrink_to_lo(), "or add a \"{}\" format string to use the message literally", "\"{}\", ".into(), Applicability::MachineApplicable, @@ -204,9 +206,9 @@ fn check_panic_str<'tcx>( cx.struct_span_lint(NON_FMT_PANIC, brace_spans.unwrap_or_else(|| vec![span]), |lint| { let mut l = lint.build(msg); l.note("this message is not used as a format string, but will be in Rust 2021"); - if span.contains(arg.span) { + if span.contains(arg_span) { l.span_suggestion( - arg.span.shrink_to_lo(), + arg_span.shrink_to_lo(), "add a \"{}\" format string to use the message literally", "\"{}\", ".into(), Applicability::MachineApplicable, @@ -231,7 +233,7 @@ fn find_delimiters<'tcx>(cx: &LateContext<'tcx>, span: Span) -> Option<(Span, Sp } fn panic_call<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>) -> (Span, Symbol) { - let mut expn = f.span.ctxt().outer_expn_data(); + let mut expn = cx.tcx.hir().span(f.hir_id).ctxt().outer_expn_data(); let mut panic_macro = kw::Empty; diff --git a/compiler/rustc_lint/src/noop_method_call.rs b/compiler/rustc_lint/src/noop_method_call.rs index 479cc00199f6a..53528b68a8a9b 100644 --- a/compiler/rustc_lint/src/noop_method_call.rs +++ b/compiler/rustc_lint/src/noop_method_call.rs @@ -85,7 +85,7 @@ impl<'tcx> LateLintPass<'tcx> for NoopMethodCall { // type are the same, implying that the method call is unnecessary. return; } - let expr_span = expr.span; + let expr_span = cx.tcx.hir().span(expr.hir_id); let note = format!( "the type `{:?}` which `{}` is being called on is the same as \ the type returned from `{}`, so the method call does not do \ @@ -93,7 +93,7 @@ impl<'tcx> LateLintPass<'tcx> for NoopMethodCall { receiver_ty, method, method, ); - let span = expr_span.with_lo(receiver.span.hi()); + let span = expr_span.with_lo(cx.tcx.hir().span(receiver.hir_id).hi()); cx.struct_span_lint(NOOP_METHOD_CALL, span, |lint| { let method = &call.ident.name; let message = format!( diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 1a06d95dd8505..74f4463f8f7b6 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -138,7 +138,8 @@ fn lint_overflowing_range_endpoint<'tcx>( // (`..=`) instead only if it is the `end` that is // overflowing and only by 1. if eps[1].expr.hir_id == expr.hir_id && lit_val - 1 == max { - cx.struct_span_lint(OVERFLOWING_LITERALS, parent_expr.span, |lint| { + let parent_expr_span = cx.tcx.hir().span(parent_expr.hir_id); + 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(cx.tcx.hir().span(eps[0].hir_id)) @@ -154,7 +155,7 @@ fn lint_overflowing_range_endpoint<'tcx>( }; let suggestion = format!("{}..={}{}", start, lit_val - 1, suffix); err.span_suggestion( - parent_expr.span, + parent_expr_span, &"use an inclusive range instead", suggestion, Applicability::MachineApplicable, @@ -216,7 +217,7 @@ fn report_bin_hex_error( negative: bool, ) { let size = Integer::from_attr(&cx.tcx, ty).size(); - cx.struct_span_lint(OVERFLOWING_LITERALS, expr.span, |lint| { + cx.struct_span_lint(OVERFLOWING_LITERALS, cx.tcx.hir().span(expr.hir_id), |lint| { let (t, actually) = match ty { attr::IntType::SignedInt(t) => { let actually = if negative { @@ -254,7 +255,7 @@ fn report_bin_hex_error( if let Some(pos) = repr_str.chars().position(|c| c == 'i' || c == 'u') { let (sans_suffix, _) = repr_str.split_at(pos); err.span_suggestion( - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("consider using the type `{}` instead", sugg_ty), format!("{}{}", sans_suffix, sugg_ty), Applicability::MachineApplicable, @@ -354,7 +355,7 @@ fn lint_int_literal<'tcx>( } } - cx.struct_span_lint(OVERFLOWING_LITERALS, e.span, |lint| { + cx.struct_span_lint(OVERFLOWING_LITERALS, cx.tcx.hir().span(e.hir_id), |lint| { let mut err = lint.build(&format!("literal out of range for `{}`", t.name_str())); err.note(&format!( "the literal `{}` does not fit into the type `{}` whose range is `{}..={}`", @@ -396,10 +397,11 @@ fn lint_uint_literal<'tcx>( match par_e.kind { hir::ExprKind::Cast(..) => { if let ty::Char = cx.typeck_results().expr_ty(par_e).kind() { - cx.struct_span_lint(OVERFLOWING_LITERALS, par_e.span, |lint| { + let par_e_span = cx.tcx.hir().span(par_e.hir_id); + cx.struct_span_lint(OVERFLOWING_LITERALS, par_e_span, |lint| { lint.build("only `u8` can be cast into `char`") .span_suggestion( - par_e.span, + par_e_span, &"use a `char` literal instead", format!("'\\u{{{:X}}}'", lit_val), Applicability::MachineApplicable, @@ -430,7 +432,7 @@ fn lint_uint_literal<'tcx>( ); return; } - cx.struct_span_lint(OVERFLOWING_LITERALS, e.span, |lint| { + cx.struct_span_lint(OVERFLOWING_LITERALS, cx.tcx.hir().span(e.hir_id), |lint| { lint.build(&format!("literal out of range for `{}`", t.name_str())) .note(&format!( "the literal `{}` does not fit into the type `{}` whose range is `{}..={}`", @@ -472,7 +474,7 @@ fn lint_literal<'tcx>( _ => bug!(), }; if is_infinite == Ok(true) { - cx.struct_span_lint(OVERFLOWING_LITERALS, e.span, |lint| { + cx.struct_span_lint(OVERFLOWING_LITERALS, cx.tcx.hir().span(e.hir_id), |lint| { lint.build(&format!("literal out of range for `{}`", t.name_str())) .note(&format!( "the literal `{}` does not fit into the type `{}` and will be converted to `{}::INFINITY`", @@ -502,7 +504,7 @@ impl<'tcx> LateLintPass<'tcx> for TypeLimits { } hir::ExprKind::Binary(binop, ref l, ref r) => { if is_comparison(binop) && !check_limits(cx, binop, &l, &r) { - cx.struct_span_lint(UNUSED_COMPARISONS, e.span, |lint| { + cx.struct_span_lint(UNUSED_COMPARISONS, cx.tcx.hir().span(e.hir_id), |lint| { lint.build("comparison is useless due to type limits").emit() }); } diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index bd345421e669f..4f8654b7a0a76 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -160,7 +160,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { }; if let Some(must_use_op) = must_use_op { - cx.struct_span_lint(UNUSED_MUST_USE, expr.span, |lint| { + cx.struct_span_lint(UNUSED_MUST_USE, cx.tcx.hir().span(expr.hir_id), |lint| { lint.build(&format!("unused {} that must be used", must_use_op)).emit() }); op_warned = true; @@ -238,7 +238,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { let mut has_emitted = false; let spans = if let hir::ExprKind::Tup(comps) = &expr.kind { debug_assert_eq!(comps.len(), tys.len()); - comps.iter().map(|e| e.span).collect() + comps.iter().map(|e| cx.tcx.hir().span(e.hir_id)).collect() } else { vec![] }; @@ -355,7 +355,8 @@ impl<'tcx> LateLintPass<'tcx> for PathStatements { 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) { + let expr_span = cx.tcx.hir().span(expr.hir_id); + if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr_span) { lint.span_suggestion( span, "use `drop` to clarify the intent", @@ -1208,7 +1209,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedAllocation { for adj in cx.typeck_results().expr_adjustments(e) { if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind { - cx.struct_span_lint(UNUSED_ALLOCATION, e.span, |lint| { + cx.struct_span_lint(UNUSED_ALLOCATION, cx.tcx.hir().span(e.hir_id), |lint| { let msg = match m { adjustment::AutoBorrowMutability::Not => { "unnecessary allocation, use `&` instead" diff --git a/compiler/rustc_middle/src/ich/impls_hir.rs b/compiler/rustc_middle/src/ich/impls_hir.rs index 44c03af4f66fa..bf00b7e353378 100644 --- a/compiler/rustc_middle/src/ich/impls_hir.rs +++ b/compiler/rustc_middle/src/ich/impls_hir.rs @@ -66,9 +66,8 @@ impl<'ctx> rustc_hir::HashStableContext for StableHashingContext<'ctx> { fn hash_hir_expr(&mut self, expr: &hir::Expr<'_>, hasher: &mut StableHasher) { self.while_hashing_hir_bodies(true, |hcx| { - let hir::Expr { hir_id: _, ref span, ref kind } = *expr; + let hir::Expr { hir_id: _, ref kind } = *expr; - span.hash_stable(hcx, hasher); kind.hash_stable(hcx, hasher); }) } diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index e7b2c9efd63cf..db9a6ce0fcfd7 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -67,10 +67,11 @@ impl<'tcx> Const<'tcx> { if let Some(lit_input) = lit_input { // If an error occurred, ignore that it's a literal and leave reporting the error up to // mir. - if let Ok(c) = tcx.at(expr.span).lit_to_const(lit_input) { + let expr_span = tcx.hir().span(expr.hir_id); + if let Ok(c) = tcx.at(expr_span).lit_to_const(lit_input) { return c; } else { - tcx.sess.delay_span_bug(expr.span, "Const::from_anon_const: couldn't lit_to_const"); + tcx.sess.delay_span_bug(expr_span, "Const::from_anon_const: couldn't lit_to_const"); } } diff --git a/compiler/rustc_mir/src/borrow_check/diagnostics/mutability_errors.rs b/compiler/rustc_mir/src/borrow_check/diagnostics/mutability_errors.rs index e67e3ae6e2800..653a04ac2cb2e 100644 --- a/compiler/rustc_mir/src/borrow_check/diagnostics/mutability_errors.rs +++ b/compiler/rustc_mir/src/borrow_check/diagnostics/mutability_errors.rs @@ -642,7 +642,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let arg_pos = args .iter() .enumerate() - .filter(|(_, arg)| arg.span == self.body.span) + .filter(|(_, arg)| hir.span(arg.hir_id) == self.body.span) .map(|(pos, _)| pos) .next(); let def_id = hir.local_def_id(item_id); @@ -683,7 +683,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { }; if let Some(span) = arg { err.span_label(span, "change this to accept `FnMut` instead of `Fn`"); - err.span_label(func.span, "expects `Fn` instead of `FnMut`"); + err.span_label(hir.span(func.hir_id), "expects `Fn` instead of `FnMut`"); if self.infcx.tcx.sess.source_map().is_multiline(self.body.span) { err.span_label(self.body.span, "in this closure"); } diff --git a/compiler/rustc_mir/src/transform/coverage/mod.rs b/compiler/rustc_mir/src/transform/coverage/mod.rs index 93133e9b7f063..879e197c13a9e 100644 --- a/compiler/rustc_mir/src/transform/coverage/mod.rs +++ b/compiler/rustc_mir/src/transform/coverage/mod.rs @@ -108,7 +108,7 @@ impl<'a, 'tcx> Instrumentor<'a, 'tcx> { fn new(pass_name: &'a str, tcx: TyCtxt<'tcx>, mir_body: &'a mut mir::Body<'tcx>) -> Self { let source_map = tcx.sess.source_map(); let (some_fn_sig, hir_body) = fn_sig_and_body(tcx, mir_body.source.def_id()); - let body_span = hir_body.value.span; + let body_span = tcx.hir().span(hir_body.value.hir_id); let source_file = source_map.lookup_source_file(body_span.lo()); let fn_sig_span = match some_fn_sig.filter(|fn_sig| { Lrc::ptr_eq(&source_file, &source_map.lookup_source_file(fn_sig.span.hi())) diff --git a/compiler/rustc_mir/src/util/spanview.rs b/compiler/rustc_mir/src/util/spanview.rs index a9a30e407b4b0..931b2f35c9516 100644 --- a/compiler/rustc_mir/src/util/spanview.rs +++ b/compiler/rustc_mir/src/util/spanview.rs @@ -99,7 +99,7 @@ where W: Write, { let def_id = body.source.def_id(); - let body_span = hir_body(tcx, def_id).value.span; + let body_span = tcx.hir().span(hir_body(tcx, def_id).value.hir_id); let mut span_viewables = Vec::new(); for (bb, data) in body.basic_blocks().iter_enumerated() { match spanview { @@ -664,7 +664,7 @@ fn fn_span<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Span { let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.as_local().expect("expected DefId is local")); let fn_decl_span = tcx.hir().span(hir_id); - let body_span = hir_body(tcx, def_id).value.span; + let body_span = tcx.hir().span(hir_body(tcx, def_id).value.hir_id); if fn_decl_span.ctxt() == body_span.ctxt() { fn_decl_span.to(body_span) } else { diff --git a/compiler/rustc_mir_build/src/build/block.rs b/compiler/rustc_mir_build/src/build/block.rs index 808c6e3ff644b..4040ef560f35d 100644 --- a/compiler/rustc_mir_build/src/build/block.rs +++ b/compiler/rustc_mir_build/src/build/block.rs @@ -110,8 +110,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // Evaluate the initializer, if present. if let Some(init) = initializer { - let initializer_span = init.span; - unpack!( block = this.in_opt_scope( opt_destruction_scope.map(|de| (de, source_info)), @@ -123,7 +121,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { remainder_span, pattern, ArmHasGuard(false), - Some((None, initializer_span)), + Some((None, init.span)), ); this.expr_into_pattern(block, pattern.clone(), init) }) diff --git a/compiler/rustc_mir_build/src/build/matches/mod.rs b/compiler/rustc_mir_build/src/build/matches/mod.rs index 6c31528be73f7..9159f2da4ca51 100644 --- a/compiler/rustc_mir_build/src/build/matches/mod.rs +++ b/compiler/rustc_mir_build/src/build/matches/mod.rs @@ -92,9 +92,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { scrutinee: &Expr<'_, 'tcx>, arms: &[Arm<'_, 'tcx>], ) -> BlockAnd<()> { - let scrutinee_span = scrutinee.span; let scrutinee_place = - unpack!(block = self.lower_scrutinee(block, scrutinee, scrutinee_span,)); + unpack!(block = self.lower_scrutinee(block, scrutinee, scrutinee.span)); let mut arm_candidates = self.create_match_candidates(scrutinee_place, &arms); @@ -103,12 +102,12 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { arm_candidates.iter_mut().map(|(_, candidate)| candidate).collect::>(); let fake_borrow_temps = - self.lower_match_tree(block, scrutinee_span, match_has_guard, &mut candidates); + self.lower_match_tree(block, scrutinee.span, match_has_guard, &mut candidates); self.lower_match_arms( destination, scrutinee_place, - scrutinee_span, + scrutinee.span, arm_candidates, self.source_info(span), fake_borrow_temps, @@ -1752,7 +1751,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { (e.span, self.test_bool(block, e, source_info)) } Guard::IfLet(pat, scrutinee) => { - let scrutinee_span = scrutinee.span; let scrutinee_place = unpack!(block = self.lower_scrutinee(block, scrutinee, scrutinee_span)); let mut guard_candidate = Candidate::new(scrutinee_place, &pat, false); @@ -1769,14 +1767,14 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { pat.span.to(arm_span.unwrap()), pat, ArmHasGuard(false), - Some((Some(&scrutinee_place), scrutinee.span)), + Some((Some(&scrutinee_place), scrutinee_span)), ); let post_guard_block = self.bind_pattern( self.source_info(pat.span), guard_candidate, None, &fake_borrow_temps, - scrutinee.span, + scrutinee_span, None, None, ); diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 23edf8dc6a84a..6c639f0e4d02a 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -48,7 +48,8 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { let expr_scope = region::Scope { id: hir_expr.hir_id.local_id, data: region::ScopeData::Node }; - debug!("Expr::make_mirror(): id={}, span={:?}", hir_expr.hir_id, hir_expr.span); + let span = self.tcx.hir().span(hir_expr.hir_id); + debug!("Expr::make_mirror(): id={}, span={:?}", hir_expr.hir_id, span); let mut expr = self.make_mirror_unadjusted(hir_expr); @@ -62,7 +63,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { expr = Expr { temp_lifetime, ty: expr.ty, - span: hir_expr.span, + span, kind: ExprKind::Scope { region_scope: expr_scope, value: self.arena.alloc(expr), @@ -77,7 +78,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { expr = Expr { temp_lifetime, ty: expr.ty, - span: hir_expr.span, + span: self.tcx.hir().span(hir_expr.hir_id), kind: ExprKind::Scope { region_scope, value: self.arena.alloc(expr), @@ -192,13 +193,13 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { // rewrite f(u, v) into FnOnce::call_once(f, (u, v)) - let method = self.method_callee(expr, fun.span, None); + let method = self.method_callee(expr, self.tcx.hir().span(fun.hir_id), None); let arg_tys = args.iter().map(|e| self.typeck_results().expr_ty_adjusted(e)); let tupled_args = Expr { ty: self.tcx.mk_tup(arg_tys), temp_lifetime, - span: expr.span, + span: self.tcx.hir().span(expr.hir_id), kind: ExprKind::Tuple { fields: self.mirror_exprs(args) }, }; @@ -209,7 +210,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { .arena .alloc_from_iter(vec![self.mirror_expr_inner(fun), tupled_args]), from_hir_call: true, - fn_span: expr.span, + fn_span: self.tcx.hir().span(expr.hir_id), } } else { let adt_data = @@ -255,7 +256,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { fun: self.mirror_expr(fun), args: self.mirror_exprs(args), from_hir_call: true, - fn_span: expr.span, + fn_span: self.tcx.hir().span(expr.hir_id), } } } @@ -335,7 +336,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { expr_ty, None, self.arena.alloc_from_iter(vec![lhs, index]), - expr.span, + self.tcx.hir().span(expr.hir_id), ) } else { ExprKind::Index { lhs: self.mirror_expr(lhs), index: self.mirror_expr(index) } @@ -350,7 +351,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { expr_ty, None, self.arena.alloc_from_iter(iter::once(arg)), - expr.span, + self.tcx.hir().span(expr.hir_id), ) } else { ExprKind::Deref { arg: self.mirror_expr(arg) } @@ -424,13 +425,21 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { } } _ => { - span_bug!(expr.span, "unexpected res: {:?}", res); + span_bug!( + self.tcx.hir().span(expr.hir_id), + "unexpected res: {:?}", + res + ); } } } }, _ => { - span_bug!(expr.span, "unexpected type for struct literal: {:?}", expr_ty); + span_bug!( + self.tcx.hir().span(expr.hir_id), + "unexpected type for struct literal: {:?}", + expr_ty + ); } }, @@ -442,7 +451,11 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { (def_id, UpvarSubsts::Generator(substs), Some(movability)) } _ => { - span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty); + span_bug!( + self.tcx.hir().span(expr.hir_id), + "closure expr w/o closure type: {:?}", + closure_ty + ); } }; @@ -492,10 +505,11 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { InlineAsmOperand::Const { expr: self.mirror_expr(expr) } } hir::InlineAsmOperand::Sym { ref expr } => { + let expr_span = self.tcx.hir().span(expr.hir_id); let qpath = match expr.kind { hir::ExprKind::Path(ref qpath) => qpath, _ => span_bug!( - expr.span, + expr_span, "asm `sym` operand should be a path, found {:?}", expr.kind ), @@ -512,7 +526,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { expr: self.arena.alloc(Expr { ty, temp_lifetime, - span: expr.span, + span: expr_span, kind: ExprKind::Literal { literal: ty::Const::zero_sized(self.tcx, ty), user_ty, @@ -528,7 +542,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { _ => { self.tcx.sess.span_err( - expr.span, + self.tcx.hir().span(expr.hir_id), "asm `sym` operand must point to a fn or static", ); @@ -538,7 +552,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { expr: self.arena.alloc(Expr { ty, temp_lifetime, - span: expr.span, + span: self.tcx.hir().span(expr.hir_id), kind: ExprKind::Literal { literal: ty::Const::zero_sized(self.tcx, ty), user_ty: None, @@ -677,7 +691,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { self.arena.alloc(Expr { temp_lifetime, ty: var_ty, - span: expr.span, + span: self.tcx.hir().span(expr.hir_id), kind: ExprKind::Literal { literal, user_ty: None, const_id: None }, }) }; @@ -704,7 +718,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { self.arena.alloc(Expr { temp_lifetime, ty: var_ty, - span: expr.span, + span: self.tcx.hir().span(expr.hir_id), kind: bin, }) } @@ -723,7 +737,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { let cast_expr = self.arena.alloc(Expr { temp_lifetime, ty: expr_ty, - span: expr.span, + span: self.tcx.hir().span(expr.hir_id), kind: cast, }); debug!("make_mirror_unadjusted: (cast) user_ty={:?}", user_ty); @@ -757,7 +771,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { hir::ExprKind::Err => unreachable!(), }; - Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind } + Expr { temp_lifetime, ty: expr_ty, span: self.tcx.hir().span(expr.hir_id), kind } } fn user_substs_applied_to_res( @@ -807,7 +821,10 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { None => { let (kind, def_id) = self.typeck_results().type_dependent_def(expr.hir_id).unwrap_or_else(|| { - span_bug!(expr.span, "no type-dependent def for method callee") + span_bug!( + self.tcx.hir().span(expr.hir_id), + "no type-dependent def for method callee" + ) }); let user_ty = self.user_substs_applied_to_res(expr.hir_id, Res::Def(kind, def_id)); debug!("method_callee: user_ty={:?}", user_ty); @@ -937,13 +954,18 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { } }; ExprKind::Deref { - arg: self.arena.alloc(Expr { ty, temp_lifetime, span: expr.span, kind }), + arg: self.arena.alloc(Expr { + ty, + temp_lifetime, + span: self.tcx.hir().span(expr.hir_id), + kind, + }), } } Res::Local(var_hir_id) => self.convert_var(var_hir_id), - _ => span_bug!(expr.span, "res `{:?}` not yet implemented", res), + _ => span_bug!(self.tcx.hir().span(expr.hir_id), "res `{:?}` not yet implemented", res), } } @@ -972,8 +994,15 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { expr: &'tcx hir::Expr<'tcx>, args: &'thir [Expr<'thir, 'tcx>], ) -> ExprKind<'thir, 'tcx> { - let fun = self.arena.alloc(self.method_callee(expr, expr.span, None)); - ExprKind::Call { ty: fun.ty, fun, args, from_hir_call: false, fn_span: expr.span } + let fun = + self.arena.alloc(self.method_callee(expr, self.tcx.hir().span(expr.hir_id), None)); + ExprKind::Call { + ty: fun.ty, + fun, + args, + from_hir_call: false, + fn_span: self.tcx.hir().span(expr.hir_id), + } } fn overloaded_place( @@ -1035,7 +1064,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { let mut captured_place_expr = Expr { temp_lifetime, ty: var_ty, - span: closure_expr.span, + span: self.tcx.hir().span(closure_expr.hir_id), kind: self.convert_var(var_hir_id), }; @@ -1058,8 +1087,12 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { } }; - captured_place_expr = - Expr { temp_lifetime, ty: proj.ty, span: closure_expr.span, kind }; + captured_place_expr = Expr { + temp_lifetime, + ty: proj.ty, + span: self.tcx.hir().span(closure_expr.hir_id), + kind, + }; } match upvar_capture { @@ -1073,7 +1106,7 @@ impl<'thir, 'tcx> Cx<'thir, 'tcx> { Expr { temp_lifetime, ty: upvar_ty, - span: closure_expr.span, + span: self.tcx.hir().span(closure_expr.hir_id), kind: ExprKind::Borrow { borrow_kind, arg: self.arena.alloc(captured_place_expr), 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 8ef1350bb2c1a..dbeb40aa0aadb 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -207,7 +207,13 @@ impl<'tcx> MatchVisitor<'_, 'tcx> { let is_empty_match = arms.is_empty(); let witnesses = report.non_exhaustiveness_witnesses; if !witnesses.is_empty() { - non_exhaustive_match(&cx, scrut_ty, scrut.span, witnesses, is_empty_match); + non_exhaustive_match( + &cx, + scrut_ty, + cx.tcx.hir().span(scrut.hir_id), + witnesses, + is_empty_match, + ); } } diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index ce9bee948fbbe..662e94de63bfd 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -522,7 +522,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| self.tcx.hir().span(e.hir_id)); let lo = lo_expr.map(|e| self.lower_range_expr(e)); let hi = hi_expr.map(|e| self.lower_range_expr(e)); @@ -858,29 +858,30 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { /// which would overflow if we tried to evaluate `128_i8` and then negate /// afterwards. fn lower_lit(&mut self, expr: &'tcx hir::Expr<'tcx>) -> PatKind<'tcx> { + let expr_span = self.tcx.hir().span(expr.hir_id); if let hir::ExprKind::Path(ref qpath) = expr.kind { - *self.lower_path(qpath, expr.hir_id, expr.span).kind + *self.lower_path(qpath, expr.hir_id, expr_span).kind } else { let (lit, neg) = match expr.kind { hir::ExprKind::ConstBlock(ref anon_const) => { let anon_const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id); let value = ty::Const::from_anon_const(self.tcx, anon_const_def_id); - return *self.const_to_pat(value, expr.hir_id, expr.span, false).kind; + return *self.const_to_pat(value, expr.hir_id, expr_span, false).kind; } hir::ExprKind::Lit(ref lit) => (lit, false), hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => { let lit = match expr.kind { hir::ExprKind::Lit(ref lit) => lit, - _ => span_bug!(expr.span, "not a literal: {:?}", expr), + _ => span_bug!(expr_span, "not a literal: {:?}", expr), }; (lit, true) } - _ => span_bug!(expr.span, "not a literal: {:?}", expr), + _ => span_bug!(expr_span, "not a literal: {:?}", expr), }; let lit_input = LitToConstInput { lit: &lit.node, ty: self.typeck_results.expr_ty(expr), neg }; - match self.tcx.at(expr.span).lit_to_const(lit_input) { + match self.tcx.at(expr_span).lit_to_const(lit_input) { Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span, false).kind, Err(LitToConstError::UnparseableFloat) => { self.errors.push(PatternError::FloatBug); diff --git a/compiler/rustc_passes/src/check_const.rs b/compiler/rustc_passes/src/check_const.rs index da713566c3121..c43c009ef1f21 100644 --- a/compiler/rustc_passes/src/check_const.rs +++ b/compiler/rustc_passes/src/check_const.rs @@ -200,7 +200,8 @@ impl<'tcx> Visitor<'tcx> for CheckConstVisitor<'tcx> { _ if self.const_kind.is_none() => {} hir::ExprKind::Loop(_, _, source, _) => { - self.const_check_violated(NonConstExpr::Loop(*source), e.span); + let span = self.tcx.hir().span(e.hir_id); + self.const_check_violated(NonConstExpr::Loop(*source), span); } hir::ExprKind::Match(_, _, source) => { @@ -214,7 +215,8 @@ impl<'tcx> Visitor<'tcx> for CheckConstVisitor<'tcx> { }; if let Some(expr) = non_const_expr { - self.const_check_violated(expr, e.span); + let span = self.tcx.hir().span(e.hir_id); + self.const_check_violated(expr, span); } } diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index eda0476bee90f..b68d96abf81e4 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -129,7 +129,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { self.insert_def_id(def.non_enum_variant().fields[index].did); } ty::Tuple(..) => {} - _ => span_bug!(lhs.span, "named field access on non-ADT"), + _ => span_bug!(self.tcx.hir().span(lhs.hir_id), "named field access on non-ADT"), } } diff --git a/compiler/rustc_passes/src/intrinsicck.rs b/compiler/rustc_passes/src/intrinsicck.rs index 0f4bb635eeefd..6260133079594 100644 --- a/compiler/rustc_passes/src/intrinsicck.rs +++ b/compiler/rustc_passes/src/intrinsicck.rs @@ -202,7 +202,7 @@ impl ExprVisitor<'tcx> { Some(asm_ty) => asm_ty, None => { let msg = &format!("cannot use value of type `{}` for inline assembly", ty); - let mut err = self.tcx.sess.struct_span_err(expr.span, msg); + let mut err = self.tcx.sess.struct_span_err(self.tcx.hir().span(expr.hir_id), msg); err.note( "only integers, floats, SIMD vectors, pointers and function pointers \ can be used as arguments for inline assembly", @@ -216,7 +216,7 @@ impl ExprVisitor<'tcx> { // possibly fail is for SIMD types which don't #[derive(Copy)]. if !ty.is_copy_modulo_regions(self.tcx.at(DUMMY_SP), self.param_env) { let msg = "arguments for inline assembly must be copyable"; - let mut err = self.tcx.sess.struct_span_err(expr.span, msg); + let mut err = self.tcx.sess.struct_span_err(self.tcx.hir().span(expr.hir_id), msg); err.note(&format!("`{}` does not implement the Copy trait", ty)); err.emit(); } @@ -233,12 +233,14 @@ impl ExprVisitor<'tcx> { if let Some((in_expr, Some(in_asm_ty))) = tied_input { if in_asm_ty != asm_ty { let msg = "incompatible types for asm inout argument"; - let mut err = self.tcx.sess.struct_span_err(vec![in_expr.span, expr.span], msg); + let in_expr_span = self.tcx.hir().span(in_expr.hir_id); + let expr_span = self.tcx.hir().span(expr.hir_id); + let mut err = self.tcx.sess.struct_span_err(vec![in_expr_span, expr_span], msg); err.span_label( - in_expr.span, + in_expr_span, &format!("type `{}`", self.typeck_results.expr_ty_adjusted(in_expr)), ); - err.span_label(expr.span, &format!("type `{}`", ty)); + err.span_label(expr_span, &format!("type `{}`", ty)); err.note( "asm inout arguments must have the same type, \ unless they are both pointers or integers of the same size", @@ -260,7 +262,7 @@ impl ExprVisitor<'tcx> { Some((_, feature)) => feature, None => { let msg = &format!("type `{}` cannot be used with this register class", ty); - let mut err = self.tcx.sess.struct_span_err(expr.span, msg); + let mut err = self.tcx.sess.struct_span_err(self.tcx.hir().span(expr.hir_id), msg); let supported_tys: Vec<_> = supported_tys.iter().map(|(t, _)| t.to_string()).collect(); err.note(&format!( @@ -292,7 +294,7 @@ impl ExprVisitor<'tcx> { if let Some(feature) = feature { if !self.tcx.sess.target_features.contains(&Symbol::intern(feature)) { let msg = &format!("`{}` target feature is not enabled", feature); - let mut err = self.tcx.sess.struct_span_err(expr.span, msg); + let mut err = self.tcx.sess.struct_span_err(self.tcx.hir().span(expr.hir_id), msg); err.note(&format!( "this is required to use type `{}` with register class `{}`", ty, @@ -328,7 +330,7 @@ impl ExprVisitor<'tcx> { |lint| { let msg = "formatting may not be suitable for sub-register argument"; let mut err = lint.build(msg); - err.span_label(expr.span, "for this argument"); + err.span_label(self.tcx.hir().span(expr.hir_id), "for this argument"); err.help(&format!( "use the `{}` modifier to have the register formatted as `{}`", suggested_modifier, suggested_result, @@ -379,7 +381,7 @@ impl ExprVisitor<'tcx> { _ => { let msg = "asm `const` arguments must be integer or floating-point values"; - self.tcx.sess.span_err(expr.span, msg); + self.tcx.sess.span_err(self.tcx.hir().span(expr.hir_id), msg); } } } @@ -419,11 +421,12 @@ impl Visitor<'tcx> for ExprVisitor<'tcx> { let res = self.typeck_results.qpath_res(qpath, expr.hir_id); if let Res::Def(DefKind::Fn, did) = res { if self.def_id_is_transmute(did) { + let expr_span = self.tcx.hir().span(expr.hir_id); let typ = self.typeck_results.node_type(expr.hir_id); let sig = typ.fn_sig(self.tcx); let from = sig.inputs().skip_binder()[0]; let to = sig.output().skip_binder(); - self.check_transmute(expr.span, from, to); + self.check_transmute(expr_span, from, to); } } } diff --git a/compiler/rustc_passes/src/liveness.rs b/compiler/rustc_passes/src/liveness.rs index b0c9140e6eed8..cebebd0abecc0 100644 --- a/compiler/rustc_passes/src/liveness.rs +++ b/compiler/rustc_passes/src/liveness.rs @@ -390,14 +390,16 @@ impl<'tcx> Visitor<'tcx> for IrMaps<'tcx> { hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => { debug!("expr {}: path that leads to {:?}", expr.hir_id, path.res); if let Res::Local(_var_hir_id) = path.res { - self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span)); + let expr_span = self.tcx.hir().span(expr.hir_id); + self.add_live_node_for_node(expr.hir_id, ExprNode(expr_span)); } intravisit::walk_expr(self, expr); } hir::ExprKind::Closure(..) => { + let expr_span = self.tcx.hir().span(expr.hir_id); // Interesting control flow (for loops can contain labeled // breaks or continues) - self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span)); + self.add_live_node_for_node(expr.hir_id, ExprNode(expr_span)); // Make a live_node for each captured variable, with the span // being the location that the variable is used. This results @@ -425,11 +427,13 @@ impl<'tcx> Visitor<'tcx> for IrMaps<'tcx> { // live nodes required for interesting control flow: hir::ExprKind::If(..) | hir::ExprKind::Match(..) | hir::ExprKind::Loop(..) => { - self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span)); + let expr_span = self.tcx.hir().span(expr.hir_id); + self.add_live_node_for_node(expr.hir_id, ExprNode(expr_span)); intravisit::walk_expr(self, expr); } hir::ExprKind::Binary(op, ..) if op.node.is_lazy() => { - self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span)); + let expr_span = self.tcx.hir().span(expr.hir_id); + self.add_live_node_for_node(expr.hir_id, ExprNode(expr_span)); intravisit::walk_expr(self, expr); } @@ -742,8 +746,9 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { }, ty::Generator(..) => return succ, _ => { + let body_span = self.ir.tcx.hir().span(body.value.hir_id); span_bug!( - body.value.span, + body_span, "{} has upvars so it should have a closure type: {:?}", hir_id, ty @@ -833,16 +838,15 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { // the construction of a closure itself is not important, // but we have to consider the closed over variables. - let caps = self - .ir - .capture_info_map - .get(&expr.hir_id) - .cloned() - .unwrap_or_else(|| span_bug!(expr.span, "no registered caps")); + let caps = + self.ir.capture_info_map.get(&expr.hir_id).cloned().unwrap_or_else(|| { + span_bug!(self.ir.tcx.hir().span(expr.hir_id), "no registered caps") + }); caps.iter().rev().fold(succ, |succ, cap| { self.init_from_succ(cap.ln, succ); - let var = self.variable(cap.var_hid, expr.span); + let expr_span = self.ir.tcx.hir().span(expr.hir_id); + let var = self.variable(cap.var_hid, expr_span); self.acc(cap.ln, var, ACC_READ | ACC_USE); cap.ln }) @@ -869,7 +873,8 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { let else_ln = self.propagate_through_opt_expr(else_opt.as_ref().map(|e| &**e), succ); let then_ln = self.propagate_through_expr(&then, succ); - let ln = self.live_node(expr.hir_id, expr.span); + let expr_span = self.ir.tcx.hir().span(expr.hir_id); + let ln = self.live_node(expr.hir_id, expr_span); self.init_from_succ(ln, else_ln); self.merge_from_succ(ln, then_ln); self.propagate_through_expr(&cond, ln) @@ -890,7 +895,8 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { // ( succ ) // // - let ln = self.live_node(expr.hir_id, expr.span); + let expr_span = self.ir.tcx.hir().span(expr.hir_id); + let ln = self.live_node(expr.hir_id, expr_span); self.init_empty(ln, succ); for arm in arms { let body_succ = self.propagate_through_expr(&arm.body, succ); @@ -917,7 +923,9 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { // Find which label this break jumps to let target = match label.target_id { Ok(hir_id) => self.break_ln.get(&hir_id), - Err(err) => span_bug!(expr.span, "loop scope error: {}", err), + Err(err) => { + span_bug!(self.ir.tcx.hir().span(expr.hir_id), "loop scope error: {}", err) + } } .cloned(); @@ -926,22 +934,33 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { match target { Some(b) => self.propagate_through_opt_expr(opt_expr.as_ref().map(|e| &**e), b), - None => span_bug!(expr.span, "`break` to unknown label"), + None => { + // FIXME: This should have been checked earlier. Once this is fixed, + // replace with `delay_span_bug`. (#62480) + self.ir + .tcx + .sess + .struct_span_err( + self.ir.tcx.hir().span(expr.hir_id), + "`break` to unknown label", + ) + .emit(); + rustc_errors::FatalError.raise() + } } } hir::ExprKind::Continue(label) => { // Find which label this expr continues to - let sc = label - .target_id - .unwrap_or_else(|err| span_bug!(expr.span, "loop scope error: {}", err)); + let sc = label.target_id.unwrap_or_else(|err| { + span_bug!(self.ir.tcx.hir().span(expr.hir_id), "loop scope error: {}", err) + }); // Now that we know the label we're going to, // look it up in the continue loop nodes table - self.cont_ln - .get(&sc) - .cloned() - .unwrap_or_else(|| span_bug!(expr.span, "continue to unknown label")) + self.cont_ln.get(&sc).cloned().unwrap_or_else(|| { + span_bug!(self.ir.tcx.hir().span(expr.hir_id), "continue to unknown label") + }) } hir::ExprKind::Assign(ref l, ref r, _) => { @@ -1012,7 +1031,8 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { hir::ExprKind::Binary(op, ref l, ref r) if op.node.is_lazy() => { let r_succ = self.propagate_through_expr(&r, succ); - let ln = self.live_node(expr.hir_id, expr.span); + let expr_span = self.ir.tcx.hir().span(expr.hir_id); + let ln = self.live_node(expr.hir_id, expr_span); self.init_from_succ(ln, succ); self.merge_from_succ(ln, r_succ); @@ -1258,7 +1278,8 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { */ // first iteration: - let ln = self.live_node(expr.hir_id, expr.span); + let expr_span = self.ir.tcx.hir().span(expr.hir_id); + let ln = self.live_node(expr.hir_id, expr_span); self.init_empty(ln, succ); debug!("propagate_through_loop: using id for loop body {} {:?}", expr.hir_id, body); @@ -1397,9 +1418,10 @@ impl<'tcx> Liveness<'_, 'tcx> { // if there is no later assignment. If this local is actually // mutable, then check for a reassignment to flag the mutability // as being used. - let ln = self.live_node(expr.hir_id, expr.span); - let var = self.variable(var_hid, expr.span); - self.warn_about_dead_assign(vec![expr.span], expr.hir_id, ln, var); + let expr_span = self.ir.tcx.hir().span(expr.hir_id); + let ln = self.live_node(expr.hir_id, expr_span); + let var = self.variable(var_hid, expr_span); + self.warn_about_dead_assign(vec![expr_span], expr.hir_id, ln, var); } } _ => { diff --git a/compiler/rustc_passes/src/loops.rs b/compiler/rustc_passes/src/loops.rs index 5122368779768..242747cd1d831 100644 --- a/compiler/rustc_passes/src/loops.rs +++ b/compiler/rustc_passes/src/loops.rs @@ -73,7 +73,8 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { self.visit_expr(e); } - if self.require_label_in_labeled_block(e.span, &break_label, "break") { + let e_span = self.hir_map.span(e.hir_id); + if self.require_label_in_labeled_block(e_span, &break_label, "break") { // If we emitted an error about an unlabeled break in a labeled // block, we don't need any further checking for this break any more return; @@ -83,7 +84,7 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { Ok(loop_id) => Some(loop_id), Err(hir::LoopIdError::OutsideLoopScope) => None, Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => { - self.emit_unlabled_cf_in_while_condition(e.span, "break"); + self.emit_unlabled_cf_in_while_condition(e_span, "break"); None } Err(hir::LoopIdError::UnresolvedLabel) => None, @@ -100,7 +101,7 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { (Some(sp), label, Some(source)) } ref r => { - span_bug!(e.span, "break label resolved to a non-loop: {:?}", r) + span_bug!(e_span, "break label resolved to a non-loop: {:?}", r) } } } else { @@ -111,13 +112,13 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { Some(kind) => { let mut err = struct_span_err!( self.sess, - e.span, + e_span, E0571, "`break` with value from a `{}` loop", kind.name() ); err.span_label( - e.span, + e_span, "can only break with a value inside `loop` or breakable block", ); if let Some(head) = head { @@ -130,7 +131,7 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { ); } err.span_suggestion( - e.span, + e_span, &format!( "use `break` on its own without a value inside this `{}` loop", kind.name(), @@ -162,7 +163,7 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { } _ => { err.span_suggestion( - break_expr.span, + self.hir_map.span(break_expr.hir_id), "alternatively, you might have meant to use the \ available loop label", label.ident.to_string(), @@ -176,10 +177,11 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { } } - self.require_break_cx("break", e.span); + self.require_break_cx("break", e_span); } hir::ExprKind::Continue(destination) => { - self.require_label_in_labeled_block(e.span, &destination, "continue"); + let e_span = self.hir_map.span(e.hir_id); + self.require_label_in_labeled_block(e_span, &destination, "continue"); match destination.target_id { Ok(loop_id) => { @@ -187,21 +189,21 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { let block_span = self.hir_map.span(block.hir_id); struct_span_err!( self.sess, - e.span, + e_span, E0696, "`continue` pointing to a labeled block" ) - .span_label(e.span, "labeled blocks cannot be `continue`'d") + .span_label(e_span, "labeled blocks cannot be `continue`'d") .span_label(block_span, "labeled block the `continue` points to") .emit(); } } Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => { - self.emit_unlabled_cf_in_while_condition(e.span, "continue"); + self.emit_unlabled_cf_in_while_condition(e_span, "continue"); } Err(_) => {} } - self.require_break_cx("continue", e.span) + self.require_break_cx("continue", e_span) } _ => intravisit::walk_expr(self, e), } diff --git a/compiler/rustc_passes/src/naked_functions.rs b/compiler/rustc_passes/src/naked_functions.rs index bde260a17a540..44404770386c7 100644 --- a/compiler/rustc_passes/src/naked_functions.rs +++ b/compiler/rustc_passes/src/naked_functions.rs @@ -129,11 +129,12 @@ impl<'tcx> Visitor<'tcx> for CheckParameters<'tcx> { hir::Path { res: hir::def::Res::Local(var_hir_id), .. }, )) = expr.kind { + let expr_span = self.tcx.hir().span(expr.hir_id); if self.params.contains(var_hir_id) { self.tcx .sess .struct_span_err( - expr.span, + expr_span, "referencing function parameters is not allowed in naked functions", ) .help("follow the calling convention in asm block to use parameters") @@ -319,6 +320,6 @@ impl<'tcx> Visitor<'tcx> for CheckInlineAssembly<'tcx> { } fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { - self.check_expr(&expr, expr.span); + self.check_expr(&expr, self.tcx.hir().span(expr.hir_id)); } } diff --git a/compiler/rustc_passes/src/region.rs b/compiler/rustc_passes/src/region.rs index 8a8ab556ebded..49885e147f514 100644 --- a/compiler/rustc_passes/src/region.rs +++ b/compiler/rustc_passes/src/region.rs @@ -405,12 +405,10 @@ fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx h if let hir::ExprKind::Yield(_, source) = &expr.kind { // Mark this expr's scope and all parent scopes as containing `yield`. let mut scope = Scope { id: expr.hir_id.local_id, data: ScopeData::Node }; + let span = visitor.tcx.hir().span(expr.hir_id); loop { - let data = YieldData { - span: expr.span, - expr_and_pat_count: visitor.expr_and_pat_count, - source: *source, - }; + let data = + YieldData { span, expr_and_pat_count: visitor.expr_and_pat_count, source: *source }; visitor.scope_tree.yield_in_scope.insert(scope, data); if visitor.pessimistic_yield { debug!("resolve_expr in pessimistic_yield - marking scope {:?} for fixup", scope); @@ -720,7 +718,7 @@ impl<'tcx> Visitor<'tcx> for RegionResolutionVisitor<'tcx> { debug!( "visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})", owner_id, - self.tcx.sess.source_map().span_to_string(body.value.span), + self.tcx.sess.source_map().span_to_string(self.tcx.hir().span(body.value.hir_id)), body_id, self.cx.parent ); diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 0bd8ad7d76804..c08074cf8eb27 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -1077,7 +1077,10 @@ impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> { }); let (use_ctxt, span) = match field { Some(field) => (field.ident.span, self.tcx.hir().span(field.hir_id)), - None => (base.span, base.span), + None => { + let base_span = self.tcx.hir().span(base.hir_id); + (base_span, base_span) + } }; self.check_field(use_ctxt, span, adt, variant_field, true); } @@ -1241,14 +1244,15 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { // Check types of expressions fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { - if self.check_expr_pat_type(expr.hir_id, expr.span) { + let expr_span = self.tcx.hir().span(expr.hir_id); + if self.check_expr_pat_type(expr.hir_id, expr_span) { // Do not check nested expressions if the error already happened. return; } match expr.kind { hir::ExprKind::Assign(_, ref rhs, _) | hir::ExprKind::Match(ref rhs, ..) => { // Do not report duplicate errors for `x = y` and `match x { ... }`. - if self.check_expr_pat_type(rhs.hir_id, rhs.span) { + if self.check_expr_pat_type(rhs.hir_id, self.tcx.hir().span(rhs.hir_id)) { return; } } @@ -1262,7 +1266,7 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { } else { self.tcx .sess - .delay_span_bug(expr.span, "no type-dependent def for method call"); + .delay_span_bug(expr_span, "no type-dependent def for method call"); } } _ => {} @@ -1334,7 +1338,7 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) { if let Some(ref init) = local.init { - if self.check_expr_pat_type(init.hir_id, init.span) { + if self.check_expr_pat_type(init.hir_id, self.tcx.hir().span(init.hir_id)) { // Do not report duplicate errors for `let x = y`. return; } 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 be4a7a84dffd4..fb81c742f11df 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -1114,8 +1114,9 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { .returns .iter() .map(|expr| { - let snip = sm.span_to_snippet(expr.span).ok()?; - Some((expr.span, format!("Box::new({})", snip))) + let expr_span = self.tcx.hir().span(expr.hir_id); + let snip = sm.span_to_snippet(expr_span).ok()?; + Some((expr_span, format!("Box::new({})", snip))) }) .collect::>>() { @@ -1171,7 +1172,8 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { for expr in &visitor.returns { if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) { let ty = self.resolve_vars_if_possible(returned_ty); - err.span_label(expr.span, &format!("this returned value is of type `{}`", ty)); + let expr_span = self.tcx.hir().span(expr.hir_id); + err.span_label(expr_span, &format!("this returned value is of type `{}`", ty)); } } } @@ -1499,7 +1501,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { ); ty_matches(ty::Binder::dummy(ty)) }) - .map(|expr| expr.span); + .map(|expr| self.tcx.hir().span(expr.hir_id)); let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause; interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span)); @@ -1930,18 +1932,18 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { ); } } - ObligationCauseCode::VariableType(hir_id) => { - let parent_node = self.tcx.hir().get_parent_node(hir_id); + ObligationCauseCode::VariableType(child_hir_id) => { + let parent_node = self.tcx.hir().get_parent_node(child_hir_id); match self.tcx.hir().find(parent_node) { Some(Node::Local(hir::Local { - init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }), + init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), hir_id, .. }), .. })) => { // When encountering an assignment of an unsized trait, like // `let x = ""[..];`, provide a suggestion to borrow the initializer in // order to use have a slice instead. err.span_suggestion_verbose( - span.shrink_to_lo(), + self.tcx.hir().span(*hir_id).shrink_to_lo(), "consider borrowing here", "&".to_owned(), Applicability::MachineApplicable, diff --git a/compiler/rustc_typeck/src/check/_match.rs b/compiler/rustc_typeck/src/check/_match.rs index cbbca3b2a0123..12b49de3f4de0 100644 --- a/compiler/rustc_typeck/src/check/_match.rs +++ b/compiler/rustc_typeck/src/check/_match.rs @@ -28,7 +28,7 @@ macro_rules! create_maybe_get_coercion_reason { ) = (&block.expr, parent) { // check that the `if` expr without `else` is the fn body's expr - if expr.span == sp { + if self.tcx.hir().span(expr.hir_id) == sp { return self.get_fn_decl(hir_id).and_then(|(fn_decl, _)| { let span = fn_decl.output.span(|id| self.tcx.hir().span(id)); let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok()?; @@ -83,8 +83,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // If there are no arms, that is a diverging match; a special case. + let expr_span = tcx.hir().span(expr.hir_id); if arms.is_empty() { - self.diverges.set(self.diverges.get() | Diverges::always(expr.span)); + self.diverges.set(self.diverges.get() | Diverges::always(expr_span)); return tcx.types.never; } @@ -94,8 +95,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let scrut_diverges = self.diverges.replace(Diverges::Maybe); // #55810: Type check patterns first so we get types for all bindings. + let scrut_span = self.tcx.hir().span(scrut.hir_id); for arm in arms { - self.check_pat_top(&arm.pat, scrutinee_ty, Some(scrut.span), true); + self.check_pat_top(&arm.pat, scrutinee_ty, Some(scrut_span), true); } // Now typecheck the blocks. @@ -121,7 +123,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Expectation::ExpectHasType(ety) if ety != self.tcx.mk_unit() => ety, _ => self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, - span: expr.span, + span: expr_span, }), }; CoerceMany::with_coercion_sites(coerce_first, arms) @@ -152,7 +154,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && if_no_else && i != 0 && self.if_fallback_coercion( - expr.span, + expr_span, &arms[0].body, &mut coercion, |hir_id, span| self.maybe_get_coercion_reason(hir_id, span), @@ -166,17 +168,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { all_arms_diverge &= self.diverges.get(); let opt_suggest_box_span = - self.opt_suggest_box_span(arm.body.span, arm_ty, orig_expected); + self.opt_suggest_box_span(tcx.hir().span(arm.body.hir_id), arm_ty, orig_expected); if source_if { let then_expr = &arms[0].body; match (i, if_no_else) { - (0, _) => coercion.coerce(self, &self.misc(expr.span), &arm.body, arm_ty), + (0, _) => coercion.coerce(self, &self.misc(expr_span), &arm.body, arm_ty), (_, true) => {} // Handled above to avoid duplicated type errors (#60254). (_, _) => { let then_ty = prior_arm_ty.unwrap(); + let expr_span = self.tcx.hir().span(expr.hir_id); let cause = self.if_cause( - expr.span, + expr_span, then_expr, &arm.body, then_ty, @@ -194,10 +197,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // but rather that there's a prior obligation that doesn't hold. 0 => (arm_span, ObligationCauseCode::BlockTailExpression(arm.body.hir_id)), _ => ( - expr.span, + self.tcx.hir().span(expr.hir_id), ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause { arm_span, - scrut_span: scrut.span, + scrut_span: self.tcx.hir().span(scrut.hir_id), semi_span, source: match_src, prior_arms: other_arms.clone(), @@ -233,10 +236,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let (Expectation::IsLast(stmt), Some(ret), true) = (orig_expected, self.ret_type_span, can_coerce_to_return_ty) { - let semi_span = expr.span.shrink_to_hi().with_hi(stmt.hi()); + let expr_span = self.tcx.hir().span(expr.hir_id); + let semi_span = expr_span.shrink_to_hi().with_hi(stmt.hi()); let mut ret_span: MultiSpan = semi_span.into(); ret_span.push_span_label( - expr.span, + expr_span, "this could be implicitly returned but it is a statement, not a \ tail expression" .to_owned(), @@ -281,8 +285,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // at a diverging expression in an arbitrary arm, // we can point at the entire `match` expression if let (Diverges::Always { .. }, hir::MatchSource::Normal) = (all_arms_diverge, match_src) { + let span = self.tcx.hir().span(expr.hir_id); all_arms_diverge = Diverges::Always { - span: expr.span, + span, custom_note: Some( "any code following this `match` expression is unreachable, as all arms diverge", ), @@ -306,7 +311,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (arm_span, mut semi_span) = if let hir::ExprKind::Block(blk, _) = &arm.body.kind { self.find_block_span(blk, prior_arm_ty) } else { - (arm.body.span, None) + (self.tcx.hir().span(arm.body.hir_id), None) }; if semi_span.is_none() && i > 0 { if let hir::ExprKind::Block(blk, _) = &arms[i - 1].body.kind { @@ -331,7 +336,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => "arm", }; for arm in arms { - self.warn_if_unreachable(arm.body.hir_id, arm.body.span, msg); + self.warn_if_unreachable(arm.body.hir_id, self.tcx.hir().span(arm.body.hir_id), msg); } } @@ -362,7 +367,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.span_label(*span, msg.as_str()); } else if let ExprKind::Block(block, _) = &then_expr.kind { if let Some(expr) = &block.expr { - err.span_label(expr.span, "found here".to_string()); + let expr_span = self.tcx.hir().span(expr.hir_id); + err.span_label(expr_span, "found here".to_string()); } } err.note("`if` expressions without `else` evaluate to `()`"); @@ -466,7 +472,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { error_sp } else { // shouldn't happen unless the parser has done something weird - else_expr.span + self.tcx.hir().span(else_expr.hir_id) }; // Compute `Span` of `then` part of `if`-expression. @@ -479,7 +485,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { then_sp } else { // shouldn't happen unless the parser has done something weird - then_expr.span + self.tcx.hir().span(then_expr.hir_id) }; // Finally construct the cause: @@ -563,7 +569,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // `check_pat` for some details. let scrut_ty = self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, - span: scrut.span, + span: self.tcx.hir().span(scrut.hir_id), }); self.check_expr_has_type_or_error(scrut, scrut_ty, |_| {}); scrut_ty @@ -576,7 +582,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected_ty: Option>, ) -> (Span, Option<(Span, StatementAsExpression)>) { if let Some(expr) = &block.expr { - (expr.span, None) + let span = self.tcx.hir().span(expr.hir_id); + (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 diff --git a/compiler/rustc_typeck/src/check/callee.rs b/compiler/rustc_typeck/src/check/callee.rs index a29f55180098a..2747bab0b9bdc 100644 --- a/compiler/rustc_typeck/src/check/callee.rs +++ b/compiler/rustc_typeck/src/check/callee.rs @@ -65,9 +65,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Expectation<'tcx>, ) -> Ty<'tcx> { let original_callee_ty = self.check_expr(callee_expr); - let expr_ty = self.structurally_resolved_type(call_expr.span, original_callee_ty); + let call_expr_span = self.tcx.hir().span(call_expr.hir_id); + let expr_ty = self.structurally_resolved_type(call_expr_span, original_callee_ty); - let mut autoderef = self.autoderef(callee_expr.span, expr_ty); + let mut autoderef = self.autoderef(call_expr_span, expr_ty); let mut result = None; while result.is_none() && autoderef.next().is_some() { result = self.try_overloaded_call_step(call_expr, callee_expr, arg_exprs, &autoderef); @@ -100,7 +101,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // we must check that return type of called functions is WF: - self.register_wf_obligation(output.into(), call_expr.span, traits::MiscObligation); + self.register_wf_obligation(output.into(), call_expr_span, traits::MiscObligation); output } @@ -134,10 +135,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // haven't yet decided on whether the closure is fn vs // fnmut vs fnonce. If so, we have to defer further processing. if self.closure_kind(substs).is_none() { + let call_expr_span = self.tcx.hir().span(call_expr.hir_id); let closure_sig = substs.as_closure().sig(); let closure_sig = self .replace_bound_vars_with_fresh_vars( - call_expr.span, + call_expr_span, infer::FnCall, closure_sig, ) @@ -211,14 +213,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { [self.tcx.mk_tup(arg_exprs.iter().map(|e| { self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, - span: e.span, + span: self.tcx.hir().span(e.hir_id), }) }))] }); let opt_input_types = opt_input_types.as_ref().map(AsRef::as_ref); + let call_expr_span = self.tcx.hir().span(call_expr.hir_id); if let Some(ok) = self.lookup_method_in_trait( - call_expr.span, + call_expr_span, method_name, trait_def_id, adjusted_ty, @@ -233,7 +236,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let ty::Ref(r, _, mutbl) = method.sig.inputs()[0].kind() { (r, mutbl) } else { - span_bug!(call_expr.span, "input to call/call_mut is not a ref?"); + span_bug!(call_expr_span, "input to call/call_mut is not a ref?"); }; let mutbl = match mutbl { @@ -300,15 +303,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let ty::Adt(adt_def, ..) = t { if adt_def.is_enum() { if let hir::ExprKind::Call(expr, _) = call_expr.kind { + let expr_span = self.tcx.hir().span(expr.hir_id); unit_variant = - self.tcx.sess.source_map().span_to_snippet(expr.span).ok(); + self.tcx.sess.source_map().span_to_snippet(expr_span).ok(); } } } + let call_expr_span = self.tcx.hir().span(call_expr.hir_id); + let callee_span = self.tcx.hir().span(callee_expr.hir_id); let mut err = type_error_struct!( self.tcx.sess, - callee_expr.span, + callee_span, callee_ty, E0618, "expected function, found {}", @@ -322,12 +328,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &mut err, call_expr.hir_id, &callee_expr.kind, - callee_expr.span, + callee_span, ); if let Some(ref path) = unit_variant { err.span_suggestion( - call_expr.span, + call_expr_span, &format!( "`{}` is a unit variant, you need to write it \ without the parenthesis", @@ -348,10 +354,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // itself another `ExprCall`, that's a clue that we might just be // missing a semicolon (Issue #51055) let call_is_multiline = - self.tcx.sess.source_map().is_multiline(call_expr.span); + self.tcx.sess.source_map().is_multiline(call_expr_span); if call_is_multiline { err.span_suggestion( - callee_expr.span.shrink_to_hi(), + callee_span.shrink_to_hi(), "consider using a semicolon here", ";".to_owned(), Applicability::MaybeIncorrect, @@ -367,7 +373,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => Res::Err, }; - err.span_label(call_expr.span, "call expression requires function"); + err.span_label(call_expr_span, "call expression requires function"); if let Some(span) = self.tcx.hir().res_span(def) { let callee_ty = callee_ty.to_string(); @@ -421,24 +427,26 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } }; + let call_expr_span = self.tcx.hir().span(call_expr.hir_id); + // Replace any late-bound regions that appear in the function // signature with region variables. We also have to // renormalize the associated types at this point, since they // previously appeared within a `Binder<>` and hence would not // have been normalized before. let fn_sig = - self.replace_bound_vars_with_fresh_vars(call_expr.span, infer::FnCall, fn_sig).0; - let fn_sig = self.normalize_associated_types_in(call_expr.span, fn_sig); + self.replace_bound_vars_with_fresh_vars(call_expr_span, infer::FnCall, fn_sig).0; + let fn_sig = self.normalize_associated_types_in(call_expr_span, fn_sig); // Call the generic checker. let expected_arg_tys = self.expected_inputs_for_expected_output( - call_expr.span, + call_expr_span, expected, fn_sig.output(), fn_sig.inputs(), ); self.check_argument_types( - call_expr.span, + call_expr_span, call_expr, fn_sig.inputs(), &expected_arg_tys[..], @@ -463,15 +471,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // do know the types expected for each argument and the return // type. + let call_expr_span = self.tcx.hir().span(call_expr.hir_id); let expected_arg_tys = self.expected_inputs_for_expected_output( - call_expr.span, + call_expr_span, expected, fn_sig.output(), fn_sig.inputs(), ); self.check_argument_types( - call_expr.span, + call_expr_span, call_expr, fn_sig.inputs(), &expected_arg_tys, @@ -491,8 +500,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Expectation<'tcx>, method_callee: MethodCallee<'tcx>, ) -> Ty<'tcx> { + let call_expr_span = self.tcx.hir().span(call_expr.hir_id); let output_type = self.check_method_argument_types( - call_expr.span, + call_expr_span, call_expr, Ok(method_callee), arg_exprs, @@ -538,13 +548,15 @@ impl<'a, 'tcx> DeferredCallResolution<'tcx> { debug!("attempt_resolution: method_callee={:?}", method_callee); + let call_expr_span = fcx.tcx.hir().span(self.call_expr.hir_id); + for (method_arg_ty, self_arg_ty) in method_sig.inputs().iter().skip(1).zip(self.fn_sig.inputs()) { - fcx.demand_eqtype(self.call_expr.span, &self_arg_ty, &method_arg_ty); + fcx.demand_eqtype(call_expr_span, &self_arg_ty, &method_arg_ty); } - fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output()); + fcx.demand_eqtype(call_expr_span, method_sig.output(), self.fn_sig.output()); let mut adjustments = self.adjustments; adjustments.extend(autoref); @@ -553,8 +565,9 @@ impl<'a, 'tcx> DeferredCallResolution<'tcx> { fcx.write_method_call(self.call_expr.hir_id, method_callee); } None => { + let call_expr_span = fcx.tcx.hir().span(self.call_expr.hir_id); span_bug!( - self.call_expr.span, + call_expr_span, "failed to find an overloaded call trait for closure call" ); } diff --git a/compiler/rustc_typeck/src/check/cast.rs b/compiler/rustc_typeck/src/check/cast.rs index 16c344e8e2b9e..46b8e010682e2 100644 --- a/compiler/rustc_typeck/src/check/cast.rs +++ b/compiler/rustc_typeck/src/check/cast.rs @@ -230,15 +230,16 @@ impl<'a, 'tcx> CastCheck<'tcx> { error_span, format!("cannot cast `{}` as `{}`", fcx.ty_to_string(self.expr_ty), cast_ty), ); - if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr.span) { + let expr_span = fcx.tcx.hir().span(self.expr.hir_id); + if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(expr_span) { err.span_suggestion( - self.expr.span, + expr_span, "dereference the expression", format!("*{}", snippet), Applicability::MaybeIncorrect, ); } else { - err.span_help(self.expr.span, "dereference the expression with `*`"); + err.span_help(expr_span, "dereference the expression with `*`"); } err.emit(); } @@ -305,7 +306,8 @@ impl<'a, 'tcx> CastCheck<'tcx> { struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`"); if self.expr_ty.is_numeric() { - match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) { + let expr_span = fcx.tcx.hir().span(self.expr.hir_id); + match fcx.tcx.sess.source_map().span_to_snippet(expr_span) { Ok(snippet) => { err.span_suggestion( self.span, @@ -363,7 +365,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { if let Some(sugg) = sugg { err.span_label(self.span, "invalid cast"); err.span_suggestion_verbose( - self.expr.span.shrink_to_lo(), + fcx.tcx.hir().span(self.expr.hir_id).shrink_to_lo(), "borrow the value for the cast to be valid", sugg, Applicability::MachineApplicable, @@ -374,7 +376,8 @@ impl<'a, 'tcx> CastCheck<'tcx> { ) { let mut label = true; // Check `impl From for self.cast_ty {}` for accurate suggestion: - if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) { + let expr_span = fcx.tcx.hir().span(self.expr.hir_id); + if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(expr_span) { if let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::from_trait) { let ty = fcx.resolve_vars_if_possible(self.cast_ty); // Erase regions to avoid panic in `prove_value` when calling @@ -519,7 +522,8 @@ impl<'a, 'tcx> CastCheck<'tcx> { } } _ => { - err.span_help(self.expr.span, "consider using a box or reference as appropriate"); + let expr_span = fcx.tcx.hir().span(self.expr.hir_id); + err.span_help(expr_span, "consider using a box or reference as appropriate"); } } err.emit(); @@ -605,10 +609,9 @@ impl<'a, 'tcx> CastCheck<'tcx> { match *self.expr_ty.kind() { ty::FnDef(..) => { // Attempt a coercion to a fn pointer type. - let f = fcx.normalize_associated_types_in( - self.expr.span, - self.expr_ty.fn_sig(fcx.tcx), - ); + let expr_span = fcx.tcx.hir().span(self.expr.hir_id); + let f = fcx + .normalize_associated_types_in(expr_span, self.expr_ty.fn_sig(fcx.tcx)); let res = fcx.try_coerce( self.expr, self.expr_ty, diff --git a/compiler/rustc_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index b00bd52930407..9497c67de11ba 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -108,7 +108,7 @@ pub(super) fn check_fn<'a, 'tcx>( fn_sig.abi, ); - let span = body.value.span; + let span = hir.span(body.value.hir_id); fn_maybe_err(tcx, span, fn_sig.abi); @@ -1577,7 +1577,7 @@ fn opaque_type_cycle_error(tcx: TyCtxt<'tcx>, id: HirId) { .returns .iter() .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some()) - .map(|expr| expr.span) + .map(|expr| tcx.hir().span(expr.hir_id)) .collect::>(); let span_len = spans.len(); if span_len == 1 { @@ -1599,7 +1599,9 @@ fn opaque_type_cycle_error(tcx: TyCtxt<'tcx>, id: HirId) { for (sp, ty) in visitor .returns .iter() - .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t))) + .filter_map(|e| { + typeck_results.node_type_opt(e.hir_id).map(|t| (tcx.hir().span(e.hir_id), t)) + }) .filter(|(_, ty)| !matches!(ty.kind(), ty::Never)) { struct VisitTypes(Vec); diff --git a/compiler/rustc_typeck/src/check/closure.rs b/compiler/rustc_typeck/src/check/closure.rs index a2433eb856ed9..45ed6bf72f513 100644 --- a/compiler/rustc_typeck/src/check/closure.rs +++ b/compiler/rustc_typeck/src/check/closure.rs @@ -132,7 +132,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None => self.infcx.next_ty_var(TypeVariableOrigin { // FIXME(eddyb) distinguish closure kind inference variables from the rest. kind: TypeVariableOriginKind::ClosureSynthetic, - span: expr.span, + span: self.tcx.hir().span(expr.hir_id), }), }; @@ -728,7 +728,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> ClosureSignatures<'tcx> { let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, bound_sig); let liberated_sig = self.inh.normalize_associated_types_in( - body.value.span, + self.tcx().hir().span(body.value.hir_id), body.value.hir_id, self.param_env, liberated_sig, diff --git a/compiler/rustc_typeck/src/check/coercion.rs b/compiler/rustc_typeck/src/check/coercion.rs index 5934d7ecec7fe..71f8875d518dc 100644 --- a/compiler/rustc_typeck/src/check/coercion.rs +++ b/compiler/rustc_typeck/src/check/coercion.rs @@ -859,7 +859,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let source = self.resolve_vars_with_obligations(expr_ty); debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target); - let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable); + let cause = + self.cause(self.tcx.hir().span(expr.hir_id), ObligationCauseCode::ExprAssignable); let coerce = Coerce::new(self, cause, allow_two_phase); let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?; @@ -973,9 +974,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } }; if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) { + let new_span = self.tcx.hir().span(new.hir_id); + // The signature must match. - let a_sig = self.normalize_associated_types_in(new.span, a_sig); - let b_sig = self.normalize_associated_types_in(new.span, b_sig); + let a_sig = self.normalize_associated_types_in(new_span, a_sig); + let b_sig = self.normalize_associated_types_in(new_span, b_sig); let sig = self .at(cause, self.param_env) .trace(prev_ty, new_ty) @@ -1452,12 +1455,13 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { // If the block is from an external macro, then do not suggest // adding a semicolon, because there's nowhere to put it. // See issue #81943. - if cond_expr.span.desugaring_kind().is_none() - && !in_external_macro(fcx.tcx.sess, cond_expr.span) + let cond_expr_span = fcx.tcx.hir().span(cond_expr.hir_id); + if cond_expr_span.desugaring_kind().is_none() + && !in_external_macro(fcx.tcx.sess, cond_expr_span) { - err.span_label(cond_expr.span, "expected this to be `()`"); + err.span_label(cond_expr_span, "expected this to be `()`"); if expr.can_have_side_effects() { - fcx.suggest_semicolon_at_end(cond_expr.span, &mut err); + fcx.suggest_semicolon_at_end(cond_expr_span, &mut err); } } } diff --git a/compiler/rustc_typeck/src/check/demand.rs b/compiler/rustc_typeck/src/check/demand.rs index 215037b1d8dcc..bed9d364b91f7 100644 --- a/compiler/rustc_typeck/src/check/demand.rs +++ b/compiler/rustc_typeck/src/check/demand.rs @@ -137,7 +137,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; let expr = expr.peel_drop_temps(); - let cause = self.misc(expr.span); + let cause = self.misc(self.tcx.hir().span(expr.hir_id)); let expr_ty = self.resolve_vars_with_obligations(checked_ty); let mut err = self.report_mismatched_types(&cause, expected, expr_ty, e); @@ -214,11 +214,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .peekable(); if compatible_variants.peek().is_some() { - if let Ok(expr_text) = self.tcx.sess.source_map().span_to_snippet(expr.span) { + let expr_span = self.tcx.hir().span(expr.hir_id); + if let Ok(expr_text) = self.tcx.sess.source_map().span_to_snippet(expr_span) { let suggestions = compatible_variants.map(|v| format!("{}({})", v, expr_text)); let msg = "try using a variant of the expected enum"; err.span_suggestions( - expr.span, + expr_span, msg, suggestions, Applicability::MaybeIncorrect, @@ -390,7 +391,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Ty<'tcx>, ) -> Option<(Span, &'static str, String, Applicability)> { let sm = self.sess().source_map(); - let sp = expr.span; + let sp = self.tcx.hir().span(expr.hir_id); if sm.is_imported(sp) { // Ignore if span is from within a macro #41858, #58298. We previously used the macro // call span, but that breaks down when the type error comes from multiple calls down. @@ -410,6 +411,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // `ExprKind::DropTemps` is semantically irrelevant for these suggestions. let expr = expr.peel_drop_temps(); + let expr_span = self.tcx.hir().span(expr.hir_id); match (&expr.kind, expected.kind(), checked_ty.kind()) { (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (exp.kind(), check.kind()) { @@ -476,7 +478,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) { // If this expression had a clone call when suggesting borrowing // we want to suggest removing it because it'd now be unnecessary. - sugg_sp = arg.span; + sugg_sp = self.tcx.hir().span(arg.hir_id); } } if let Ok(src) = sm.span_to_snippet(sugg_sp) { @@ -514,9 +516,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // | | // consider dereferencing here: `*opt` | // expected mutable reference, found enum `Option` - if let Ok(src) = sm.span_to_snippet(left_expr.span) { + let left_expr_span = self.tcx.hir().span(left_expr.hir_id); + if let Ok(src) = sm.span_to_snippet(left_expr_span) { return Some(( - left_expr.span, + left_expr_span, "consider dereferencing here to assign to the mutable \ borrowed piece of memory", format!("*{}", src), @@ -553,7 +556,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { // We have `&T`, check if what was expected was `T`. If so, // we may want to suggest removing a `&`. - if sm.is_imported(expr.span) { + let expr_span = self.tcx.hir().span(expr.hir_id); + if sm.is_imported(expr_span) { if let Ok(src) = sm.span_to_snippet(sp) { if let Some(src) = src.strip_prefix('&') { return Some(( @@ -566,7 +570,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } return None; } - if let Ok(code) = sm.span_to_snippet(expr.span) { + if let Ok(code) = sm.span_to_snippet(expr_span) { return Some(( sp, "consider removing the borrow", @@ -620,14 +624,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } } - _ if sp == expr.span && !is_macro => { + _ if sp == expr_span && !is_macro => { if let Some(steps) = self.deref_steps(checked_ty, expected) { let expr = expr.peel_blocks(); if steps == 1 { if let hir::ExprKind::AddrOf(_, mutbl, inner) = expr.kind { // If the expression has `&`, removing it would fix the error - let prefix_span = expr.span.with_hi(inner.span.lo()); + let expr_span = self.tcx.hir().span(expr.hir_id); + let prefix_span = + expr_span.with_hi(self.tcx.hir().span(inner.hir_id).lo()); let message = match mutbl { hir::Mutability::Not => "consider removing the `&`", hir::Mutability::Mut => "consider removing the `&mut`", @@ -645,7 +651,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { sp, ) { // For this suggestion to make sense, the type would need to be `Copy`. - if let Ok(code) = sm.span_to_snippet(expr.span) { + if let Ok(code) = sm.span_to_snippet(expr_span) { let message = if checked_ty.is_region_ptr() { "consider dereferencing the borrow" } else { @@ -657,7 +663,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { format!("*{}", code) }; return Some(( - expr.span, + expr_span, message, suggestion, Applicability::MachineApplicable, @@ -680,12 +686,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected_ty: Ty<'tcx>, expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>, ) -> bool { - if self.tcx.sess.source_map().is_imported(expr.span) { + let expr_span = self.tcx.hir().span(expr.hir_id); + if self.tcx.sess.source_map().is_imported(expr_span) { // Ignore if span is from within a macro. return false; } - let src = if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) { + let src = if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr_span) { src } else { return false; @@ -816,7 +823,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.tcx .sess .source_map() - .span_to_snippet(expr.span) + .span_to_snippet(self.tcx.hir().span(expr.hir_id)) .ok() .map(|src| (expr, src)) }); @@ -827,13 +834,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { "you can convert `{}` from `{}` to `{}`, matching the type of `{}`", lhs_src, expected_ty, checked_ty, src ); - let suggestion = format!("{}::from({})", checked_ty, lhs_src); - (lhs_expr.span, msg, suggestion) + let suggestion = format!("{}::from({})", checked_ty, lhs_src,); + (self.tcx.hir().span(lhs_expr.hir_id), msg, suggestion) } else { let msg = format!("{} and panic if the converted value doesn't fit", msg); let suggestion = format!("{}{}.try_into().unwrap()", prefix, with_opt_paren(&src)); - (expr.span, msg, suggestion) + (expr_span, msg, suggestion) }; err.span_suggestion(span, &msg, suggestion, Applicability::MachineApplicable); }; @@ -873,7 +880,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { into_suggestion.clone() }; - err.span_suggestion(expr.span, msg, suggestion, Applicability::MachineApplicable); + err.span_suggestion(expr_span, msg, suggestion, Applicability::MachineApplicable); }; match (&expected_ty.kind(), &checked_ty.kind()) { @@ -928,7 +935,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { suggest_to_change_suffix_or_into(err, false, true); } else if literal_is_ty_suffixed(expr) { err.span_suggestion( - expr.span, + expr_span, &lit_msg, suffix_suggestion, Applicability::MachineApplicable, @@ -936,7 +943,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else if can_cast { // Missing try_into implementation for `f64` to `f32` err.span_suggestion( - expr.span, + expr_span, &format!("{}, producing the closest possible value", cast_msg), cast_suggestion, Applicability::MaybeIncorrect, // lossy conversion @@ -947,7 +954,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => { if literal_is_ty_suffixed(expr) { err.span_suggestion( - expr.span, + expr_span, &lit_msg, suffix_suggestion, Applicability::MachineApplicable, @@ -955,7 +962,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else if can_cast { // Missing try_into implementation for `{float}` to `{integer}` err.span_suggestion( - expr.span, + expr_span, &format!("{}, rounding the float towards zero", msg), cast_suggestion, Applicability::MaybeIncorrect, // lossy conversion @@ -967,7 +974,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // if `found` is `None` (meaning found is `usize`), don't suggest `.into()` if exp.bit_width() > found.bit_width().unwrap_or(256) { err.span_suggestion( - expr.span, + expr_span, &format!( "{}, producing the floating point representation of the integer", msg, @@ -977,7 +984,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); } else if literal_is_ty_suffixed(expr) { err.span_suggestion( - expr.span, + expr_span, &lit_msg, suffix_suggestion, Applicability::MachineApplicable, @@ -985,7 +992,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { // Missing try_into implementation for `{integer}` to `{float}` err.span_suggestion( - expr.span, + expr_span, &format!( "{}, producing the floating point representation of the integer, rounded if necessary", @@ -1001,7 +1008,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // if `found` is `None` (meaning found is `isize`), don't suggest `.into()` if exp.bit_width() > found.bit_width().unwrap_or(256) { err.span_suggestion( - expr.span, + expr_span, &format!( "{}, producing the floating point representation of the integer", &msg, @@ -1011,7 +1018,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); } else if literal_is_ty_suffixed(expr) { err.span_suggestion( - expr.span, + expr_span, &lit_msg, suffix_suggestion, Applicability::MachineApplicable, @@ -1019,7 +1026,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { // Missing try_into implementation for `{integer}` to `{float}` err.span_suggestion( - expr.span, + expr_span, &format!( "{}, producing the floating point representation of the integer, \ rounded if necessary", diff --git a/compiler/rustc_typeck/src/check/expr.rs b/compiler/rustc_typeck/src/check/expr.rs index 72926c5d5daf9..298b29b396ad7 100644 --- a/compiler/rustc_typeck/src/check/expr.rs +++ b/compiler/rustc_typeck/src/check/expr.rs @@ -50,7 +50,7 @@ use rustc_trait_selection::traits::{self, ObligationCauseCode}; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn check_expr_eq_type(&self, expr: &'tcx hir::Expr<'tcx>, expected: Ty<'tcx>) { let ty = self.check_expr_with_hint(expr, expected); - self.demand_eqtype(expr.span, expected, ty); + self.demand_eqtype(self.tcx.hir().span(expr.hir_id), expected, ty); } pub fn check_expr_has_type_or_error( @@ -80,7 +80,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); let adj_ty = self.next_diverging_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::AdjustmentType, - span: expr.span, + span: self.tcx.hir().span(expr.hir_id), }); self.apply_adjustments( expr, @@ -89,7 +89,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty = adj_ty; } - if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) { + if let Some(mut err) = + self.demand_suptype_diag(self.tcx.hir().span(expr.hir_id), expected_ty, ty) + { let expr = expr.peel_drop_temps(); self.suggest_deref_ref_or_into(&mut err, expr, expected_ty, ty, None); extend_err(&mut err); @@ -163,13 +165,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Expectation<'tcx>, ) -> Ty<'tcx> { debug!(">> type-checking: expr={:?} expected={:?}", expr, expected); + let expr_span = self.tcx.hir().span(expr.hir_id); // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block // without the final expr (e.g. `try { return; }`). We don't want to generate an // unreachable_code lint for it since warnings for autogenerated code are confusing. let is_try_block_generated_unit_expr = match expr.kind { - ExprKind::Call(_, args) if expr.span.is_desugaring(DesugaringKind::TryBlock) => { - args.len() == 1 && args[0].span.is_desugaring(DesugaringKind::TryBlock) + ExprKind::Call(_, args) if expr_span.is_desugaring(DesugaringKind::TryBlock) => { + args.len() == 1 + && self.tcx.hir().span(args[0].hir_id).is_desugaring(DesugaringKind::TryBlock) } _ => false, @@ -177,7 +181,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Warn for expressions after diverging siblings. if !is_try_block_generated_unit_expr { - self.warn_if_unreachable(expr.hir_id, expr.span, "expression"); + self.warn_if_unreachable(expr.hir_id, expr_span, "expression"); } // Hide the outer diverging and has_errors flags. @@ -192,17 +196,19 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // If `expr` is a result of desugaring the try block and is an ok-wrapped // diverging expression (e.g. it arose from desugaring of `try { return }`), // we skip issuing a warning because it is autogenerated code. - ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {} - ExprKind::Call(callee, _) => self.warn_if_unreachable(expr.hir_id, callee.span, "call"), + ExprKind::Call(..) if expr_span.is_desugaring(DesugaringKind::TryBlock) => {} + ExprKind::Call(callee, _) => { + self.warn_if_unreachable(expr.hir_id, self.tcx.hir().span(callee.hir_id), "call") + } ExprKind::MethodCall(_, ref span, _, _) => { self.warn_if_unreachable(expr.hir_id, *span, "call") } - _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"), + _ => self.warn_if_unreachable(expr.hir_id, expr_span, "expression"), } // Any expression that produces a value of type `!` must have diverged if ty.is_never() { - self.diverges.set(self.diverges.get() | Diverges::always(expr.span)); + self.diverges.set(self.diverges.get() | Diverges::always(expr_span)); } // Record the type, which applies it effects. @@ -283,9 +289,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.check_expr_eq_type(&e, ty); ty } - ExprKind::If(cond, then_expr, opt_else_expr) => { - self.check_then_else(cond, then_expr, opt_else_expr, expr.span, expected) - } + ExprKind::If(cond, then_expr, opt_else_expr) => self.check_then_else( + cond, + then_expr, + opt_else_expr, + self.tcx.hir().span(expr.hir_id), + expected, + ), ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected), ExprKind::Array(args) => self.check_expr_array(args, expected, expr), ExprKind::ConstBlock(ref anon_const) => self.to_const(anon_const).ty, @@ -327,7 +337,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut oprnd_t = self.check_expr_with_expectation(&oprnd, expected_inner); if !oprnd_t.references_error() { - oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t); + let expr_span = self.tcx.hir().span(expr.hir_id); + oprnd_t = self.structurally_resolved_type(expr_span, oprnd_t); match unop { hir::UnOp::Deref => { if let Some(ty) = self.lookup_derefing(expr, oprnd, oprnd_t) { @@ -335,13 +346,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { let mut err = type_error_struct!( tcx.sess, - expr.span, + expr_span, oprnd_t, E0614, "type `{}` cannot be dereferenced", oprnd_t, ); - let sp = tcx.sess.source_map().start_point(expr.span); + let sp = tcx.sess.source_map().start_point(expr_span); if let Some(sp) = tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) { @@ -418,7 +429,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // this time with enough precision to check that the value // whose address was taken can actually be made to live as long // as it needs to live. - let region = self.next_region_var(infer::AddrOfRegion(expr.span)); + let expr_span = self.tcx.hir().span(expr.hir_id); + let region = self.next_region_var(infer::AddrOfRegion(expr_span)); self.tcx.mk_ref(region, tm) } } @@ -449,7 +461,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .map_or(false, |x| x.iter().any(|adj| matches!(adj.kind, Adjust::Deref(_)))) }); if !is_named { - self.tcx.sess.emit_err(AddressOfTemporaryTaken { span: oprnd.span }) + let oprnd_span = self.tcx.hir().span(oprnd.hir_id); + self.tcx.sess.emit_err(AddressOfTemporaryTaken { span: oprnd_span }) } } @@ -458,22 +471,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { lang_item: hir::LangItem, expr: &'tcx hir::Expr<'tcx>, ) -> Ty<'tcx> { - self.resolve_lang_item_path(lang_item, expr.span, expr.hir_id).1 + self.resolve_lang_item_path(lang_item, self.tcx.hir().span(expr.hir_id), expr.hir_id).1 } fn check_expr_path(&self, qpath: &hir::QPath<'_>, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> { let tcx = self.tcx; - let (res, opt_ty, segs) = self.resolve_ty_and_res_ufcs(qpath, expr.hir_id, expr.span); + let expr_span = self.tcx.hir().span(expr.hir_id); + let (res, opt_ty, segs) = self.resolve_ty_and_res_ufcs(qpath, expr.hir_id, expr_span); let ty = match res { Res::Err => { self.set_tainted_by_errors(); tcx.ty_error() } Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => { - report_unexpected_variant_res(tcx, res, expr.span); + report_unexpected_variant_res(tcx, res, expr_span); tcx.ty_error() } - _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0, + _ => self.instantiate_value_path(segs, opt_ty, res, expr_span, expr.hir_id).0, }; if let ty::FnDef(..) = ty.kind() { @@ -494,14 +508,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // with fresh vars. let input = self .replace_bound_vars_with_fresh_vars( - expr.span, + expr_span, infer::LateBoundRegionConversionTime::FnCall, fn_sig.input(i), ) .0; self.require_type_is_sized_deferred( input, - expr.span, + expr_span, traits::SizedArgumentType(None), ); } @@ -514,12 +528,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // with fresh vars. let output = self .replace_bound_vars_with_fresh_vars( - expr.span, + expr_span, infer::LateBoundRegionConversionTime::FnCall, fn_sig.output(), ) .0; - self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType); + self.require_type_is_sized_deferred(output, expr_span, traits::SizedReturnType); } // We always require that the type provided as the value for @@ -537,6 +551,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr: &'tcx hir::Expr<'tcx>, ) -> Ty<'tcx> { let tcx = self.tcx; + let expr_span = self.tcx.hir().span(expr.hir_id); if let Ok(target_id) = destination.target_id { let (e_ty, cause); if let Some(e) = expr_opt { @@ -552,7 +567,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None => { // Avoid ICE when `break` is inside a closure (#65383). return tcx.ty_error_with_message( - expr.span, + expr_span, "break was outside loop, but no error was emitted", ); } @@ -566,12 +581,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Recurse without `enclosing_breakables` borrowed. e_ty = self.check_expr_with_hint(e, coerce_to); - cause = self.misc(e.span); + cause = self.misc(self.tcx.hir().span(e.hir_id)); } else { // Otherwise, this is a break *without* a value. That's // always legal, and is equivalent to `break ()`. e_ty = tcx.mk_unit(); - cause = self.misc(expr.span); + cause = self.misc(expr_span); } // Now that we have type-checked `expr_opt`, borrow @@ -583,7 +598,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None => { // Avoid ICE when `break` is inside a closure (#65383). return tcx.ty_error_with_message( - expr.span, + expr_span, "break was outside loop, but no error was emitted", ); } @@ -608,7 +623,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .map(|l| format!(" {}", l.ident)) .unwrap_or_else(String::new); err.span_suggestion( - expr.span, + expr_span, "give it a value of the expected type", format!("break{} {}", label, val), Applicability::HasPlaceholders, @@ -642,7 +657,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // inside a loop at all, which is caught by the // loop-checking pass. let err = self.tcx.ty_error_with_message( - expr.span, + expr_span, "break was outside loop, but no error was emitted", ); @@ -670,19 +685,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr_opt: Option<&'tcx hir::Expr<'tcx>>, expr: &'tcx hir::Expr<'tcx>, ) -> Ty<'tcx> { + let expr_span = self.tcx.hir().span(expr.hir_id); if self.ret_coercion.is_none() { - self.tcx.sess.emit_err(ReturnStmtOutsideOfFnBody { span: expr.span }); + self.tcx.sess.emit_err(ReturnStmtOutsideOfFnBody { span: expr_span }); } else if let Some(e) = expr_opt { if self.ret_coercion_span.get().is_none() { - self.ret_coercion_span.set(Some(e.span)); + self.ret_coercion_span.set(Some(self.tcx.hir().span(e.hir_id))); } self.check_return_expr(e); } else { let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut(); if self.ret_coercion_span.get().is_none() { - self.ret_coercion_span.set(Some(expr.span)); + self.ret_coercion_span.set(Some(expr_span)); } - let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression); + let cause = self.cause(expr_span, ObligationCauseCode::ReturnNoExpression); if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) { coercion.coerce_forced_unit( self, @@ -706,15 +722,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } pub(super) fn check_return_expr(&self, return_expr: &'tcx hir::Expr<'tcx>) { + let return_expr_span = self.tcx.hir().span(return_expr.hir_id); let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| { - span_bug!(return_expr.span, "check_return_expr called outside fn body") + span_bug!(return_expr_span, "check_return_expr called outside fn body") }); let ret_ty = ret_coercion.borrow().expected_ty(); let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty); ret_coercion.borrow_mut().coerce( self, - &self.cause(return_expr.span, ObligationCauseCode::ReturnValue(return_expr.hir_id)), + &self.cause(return_expr_span, ObligationCauseCode::ReturnValue(return_expr.hir_id)), return_expr, return_expr_ty, ); @@ -736,7 +753,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { "invalid left-hand side of assignment", DiagnosticId::Error(err_code.into()), ); - err.span_label(lhs.span, "cannot assign to this expression"); + err.span_label(self.tcx.hir().span(lhs.hir_id), "cannot assign to this expression"); err.emit(); } @@ -752,7 +769,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> Ty<'tcx> { let cond_ty = self.check_expr_has_type_or_error(cond_expr, self.tcx.types.bool, |_| {}); - self.warn_if_unreachable(cond_expr.hir_id, then_expr.span, "block in `if` expression"); + self.warn_if_unreachable( + cond_expr.hir_id, + self.tcx.hir().span(then_expr.hir_id), + "block in `if` expression", + ); let cond_diverges = self.diverges.get(); self.diverges.set(Diverges::Maybe); @@ -777,8 +798,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let else_ty = self.check_expr_with_expectation(else_expr, expected); let else_diverges = self.diverges.get(); - let opt_suggest_box_span = - self.opt_suggest_box_span(else_expr.span, else_ty, orig_expected); + let opt_suggest_box_span = self.opt_suggest_box_span( + self.tcx.hir().span(else_expr.hir_id), + else_ty, + orig_expected, + ); let if_cause = self.if_cause(sp, then_expr, else_expr, then_ty, else_ty, opt_suggest_box_span); @@ -809,13 +833,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { rhs: &'tcx hir::Expr<'tcx>, span: &Span, ) -> Ty<'tcx> { - let expected_ty = expected.coercion_target_type(self, expr.span); + let expr_span = self.tcx.hir().span(expr.hir_id); + let expected_ty = expected.coercion_target_type(self, expr_span); if expected_ty == self.tcx.types.bool { // The expected type is `bool` but this will result in `()` so we can reasonably // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`. // The likely cause of this is `if foo = bar { .. }`. let actual_ty = self.tcx.mk_unit(); - let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap(); + let mut err = self.demand_suptype_diag(expr_span, expected_ty, actual_ty).unwrap(); let lhs_ty = self.check_expr(&lhs); let rhs_ty = self.check_expr(&rhs); let (applicability, eq) = if self.can_coerce(rhs_ty, lhs_ty) { @@ -828,7 +853,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut span_err = || { // Likely `if let` intended. err.span_suggestion_verbose( - expr.span.shrink_to_lo(), + self.tcx.hir().span(expr.hir_id).shrink_to_lo(), "you might have meant to use pattern matching", "let ".to_string(), applicability, @@ -856,7 +881,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); } - if self.sess().if_let_suggestions.borrow().get(&expr.span).is_some() { + if self + .sess() + .if_let_suggestions + .borrow() + .get(&self.tcx.hir().span(expr.hir_id)) + .is_some() + { // We already emitted an `if let` suggestion due to an identifier not found. err.delay_as_bug(); } else { @@ -870,7 +901,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace); let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty, Some(lhs)); - self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized); + self.require_type_is_sized( + lhs_ty, + self.tcx.hir().span(lhs.hir_id), + traits::AssignmentLhsSized, + ); if lhs_ty.references_error() || rhs_ty.references_error() { self.tcx.ty_error() @@ -937,7 +972,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let rcvr = &args[0]; let rcvr_t = self.check_expr(&rcvr); // no need to check for bot/err -- callee does that - let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t); + let rcvr_t = self.structurally_resolved_type(self.tcx.hir().span(args[0].hir_id), rcvr_t); let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr) { Ok(method) => { @@ -1039,7 +1074,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Defer other checks until we're done type checking. let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut(); let t_span = self.tcx.hir().span(t.hir_id); - match cast::CastCheck::new(self, e, t_expr, t_cast, t_span, expr.span) { + let expr_span = self.tcx.hir().span(expr.hir_id); + match cast::CastCheck::new(self, e, t_expr, t_cast, t_span, expr_span) { Ok(cast_check) => { deferred_cast_checks.push(cast_check); t_cast @@ -1055,6 +1091,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Expectation<'tcx>, expr: &'tcx hir::Expr<'tcx>, ) -> Ty<'tcx> { + let expr_span = self.tcx.hir().span(expr.hir_id); let element_ty = if !args.is_empty() { let coerce_to = expected .to_option(self) @@ -1065,21 +1102,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .unwrap_or_else(|| { self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, - span: expr.span, + span: expr_span, }) }); let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args); assert_eq!(self.diverges.get(), Diverges::Maybe); for e in args { let e_ty = self.check_expr_with_hint(e, coerce_to); - let cause = self.misc(e.span); + let cause = self.misc(self.tcx.hir().span(e.hir_id)); coerce.coerce(self, &cause, e, e_ty); } coerce.complete(self) } else { self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, - span: expr.span, + span: expr_span, }) }; self.tcx.mk_array(element_ty, args.len() as u64) @@ -1111,7 +1148,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None => { let ty = self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, - span: element.span, + span: self.tcx.hir().span(element.hir_id), }); let element_ty = self.check_expr_has_type_or_error(&element, ty, |_| {}); (element_ty, ty) @@ -1151,7 +1188,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if tuple.references_error() { self.tcx.ty_error() } else { - self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized); + let expr_span = self.tcx.hir().span(expr.hir_id); + self.require_type_is_sized(tuple, expr_span, traits::TupleInitializerSized); tuple } } @@ -1173,12 +1211,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return self.tcx.ty_error(); }; + let expr_span = self.tcx.hir().span(expr.hir_id); + // Prohibit struct expressions when non-exhaustive flag is set. let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type"); if !adt.did.is_local() && variant.is_field_list_non_exhaustive() { self.tcx .sess - .emit_err(StructExprNonExhaustive { span: expr.span, what: adt.variant_descr() }); + .emit_err(StructExprNonExhaustive { span: expr_span, what: adt.variant_descr() }); } let error_happened = self.check_expr_struct_fields( @@ -1204,7 +1244,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .iter() .map(|f| { self.normalize_associated_types_in( - expr.span, + expr_span, f.ty(self.tcx, substs), ) }) @@ -1216,14 +1256,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .insert(expr.hir_id, fru_field_types); } _ => { + let base_expr_span = self.tcx.hir().span(base_expr.hir_id); self.tcx .sess - .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span }); + .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr_span }); } } } } - self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized); + self.require_type_is_sized(adt_ty, expr_span, traits::StructInitializerSized); adt_ty } @@ -1592,9 +1633,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> Ty<'tcx> { debug!("check_field(expr: {:?}, base: {:?}, field: {:?})", expr, base, field); let expr_t = self.check_expr(base); - let expr_t = self.structurally_resolved_type(base.span, expr_t); + let expr_t = self.structurally_resolved_type(self.tcx.hir().span(base.hir_id), expr_t); + let expr_span = self.tcx.hir().span(expr.hir_id); let mut private_candidate = None; - let mut autoderef = self.autoderef(expr.span, expr_t); + let mut autoderef = self.autoderef(expr_span, expr_t); while let Some((base_t, _)) = autoderef.next() { debug!("base_t: {:?}", base_t); match base_t.kind() { @@ -1607,7 +1649,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fields.iter().position(|f| f.ident.normalize_to_macros_2_0() == ident) { let field = &fields[index]; - let field_ty = self.field_ty(expr.span, field, substs); + let field_ty = self.field_ty(expr_span, field, substs); // Save the index of all fields regardless of their visibility in case // of error recovery. self.write_field_index(expr.hir_id, index); @@ -1616,7 +1658,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.apply_adjustments(base, adjustments); self.register_predicates(autoderef.into_obligations()); - self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span); + self.tcx.check_stability(field.did, Some(expr.hir_id), expr_span); return field_ty; } private_candidate = Some((base_def.did, field_ty)); @@ -1689,7 +1731,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { "field not available in `impl Future`, but it is available in its `Output`", ); err.span_suggestion_verbose( - base.span.shrink_to_hi(), + self.tcx.hir().span(base.hir_id).shrink_to_hi(), "consider `await`ing on the `Future` and access the field of its `Output`", ".await".to_string(), Applicability::MaybeIncorrect, @@ -1860,7 +1902,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let (Some(len), Ok(user_index)) = (len.try_eval_usize(self.tcx, self.param_env), field.as_str().parse::()) { - if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span) { + if let Ok(base) = + self.tcx.sess.source_map().span_to_snippet(self.tcx.hir().span(base.hir_id)) + { let help = "instead of using tuple indexing, use array indexing"; let suggestion = format!("{}[{}]", base, field); let applicability = if len < user_index { @@ -1868,7 +1912,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { Applicability::MaybeIncorrect }; - err.span_suggestion(expr.span, help, suggestion, applicability); + err.span_suggestion( + self.tcx.hir().span(expr.hir_id), + help, + suggestion, + applicability, + ); } } } @@ -1880,10 +1929,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { base: &hir::Expr<'_>, field: Ident, ) { - if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span) { + if let Ok(base) = + self.tcx.sess.source_map().span_to_snippet(self.tcx.hir().span(base.hir_id)) + { let msg = format!("`{}` is a raw pointer; try dereferencing it", base); let suggestion = format!("(*{}).{}", base, field); - err.span_suggestion(expr.span, &msg, suggestion, Applicability::MaybeIncorrect); + err.span_suggestion( + self.tcx.hir().span(expr.hir_id), + &msg, + suggestion, + Applicability::MaybeIncorrect, + ); } } @@ -2017,7 +2073,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else if idx_t.references_error() { idx_t } else { - let base_t = self.structurally_resolved_type(base.span, base_t); + let base_span = self.tcx.hir().span(base.hir_id); + let base_t = self.structurally_resolved_type(base_span, base_t); match self.lookup_indexing(expr, base, base_t, idx_t) { Some((index_ty, element_ty)) => { // two-phase not needed because index_ty is never mutable @@ -2025,9 +2082,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { element_ty } None => { + let expr_span = self.tcx.hir().span(expr.hir_id); let mut err = type_error_struct!( self.tcx.sess, - expr.span, + expr_span, base_t, E0608, "cannot index into a value of type `{}`", @@ -2040,10 +2098,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // fixed expression: if let ExprKind::Lit(ref lit) = idx.kind { if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node { - let snip = self.tcx.sess.source_map().span_to_snippet(base.span); + let snip = self.tcx.sess.source_map().span_to_snippet(base_span); if let Ok(snip) = snip { err.span_suggestion( - expr.span, + expr_span, "to access tuple elements, use", format!("{}.{}", snip, i), Applicability::MachineApplicable, @@ -2087,7 +2145,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.tcx.mk_unit() } _ => { - self.tcx.sess.emit_err(YieldExprOutsideOfGenerator { span: expr.span }); + let expr_span = self.tcx.hir().span(expr.hir_id); + self.tcx.sess.emit_err(YieldExprOutsideOfGenerator { span: expr_span }); // Avoid expressions without types during writeback (#78653). self.check_expr(value); self.tcx.mk_unit() @@ -2098,11 +2157,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) { let needs = if is_input { Needs::None } else { Needs::MutPlace }; let ty = self.check_expr_with_needs(expr, needs); - self.require_type_is_sized(ty, expr.span, traits::InlineAsmSized); + let expr_span = self.tcx.hir().span(expr.hir_id); + self.require_type_is_sized(ty, expr_span, traits::InlineAsmSized); if !is_input && !expr.is_syntactic_place_expr() { - let mut err = self.tcx.sess.struct_span_err(expr.span, "invalid asm output"); - err.span_label(expr.span, "cannot assign to this expression"); + let mut err = self.tcx.sess.struct_span_err(expr_span, "invalid asm output"); + err.span_label(expr_span, "cannot assign to this expression"); err.emit(); } @@ -2114,7 +2174,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // allows them to be inferred based on how they are used later in the // function. if is_input { - let ty = self.structurally_resolved_type(expr.span, &ty); + let ty = self.structurally_resolved_type(expr_span, &ty); match *ty.kind() { ty::FnDef(..) => { let fnptr_ty = self.tcx.mk_fn_ptr(ty.fn_sig(self.tcx)); diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs index f7417b354e7a3..00d95637a9fba 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs @@ -555,7 +555,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for arg in substs.iter().filter(|arg| { matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..)) }) { - self.register_wf_obligation(arg, expr.span, traits::MiscObligation); + self.register_wf_obligation( + arg, + self.tcx.hir().span(expr.hir_id), + traits::MiscObligation, + ); } } @@ -1013,7 +1017,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ), ); sp.push_span_label( - rcvr.span, + self.tcx.hir().span(rcvr.hir_id), "you probably want to use this value after calling the method...".to_string(), ); err.span_note( diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs index 95d485b8d4fbe..63afaead25156 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs @@ -109,7 +109,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // All the input types from the fn signature must outlive the call // so as to validate implied bounds. for (&fn_input_ty, arg_expr) in fn_inputs.iter().zip(args.iter()) { - self.register_wf_obligation(fn_input_ty.into(), arg_expr.span, traits::MiscObligation); + self.register_wf_obligation( + fn_input_ty.into(), + tcx.hir().span(arg_expr.hir_id), + traits::MiscObligation, + ); } let expected_arg_count = fn_inputs.len(); @@ -120,7 +124,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { c_variadic: bool, sugg_unit: bool| { let (span, start_span, args) = match &expr.kind { - hir::ExprKind::Call(hir::Expr { span, .. }, args) => (*span, *span, &args[..]), + hir::ExprKind::Call(hir::Expr { hir_id, .. }, args) => { + let span = tcx.hir().span(*hir_id); + (span, span, &args[..]) + } hir::ExprKind::MethodCall(path_segment, span, args, _) => ( *span, // `sp` doesn't point at the whole `foo.bar()`, only at `bar`. @@ -151,7 +158,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // ^^^ - - - supplied 3 arguments // | // expected 2 arguments - args.iter().map(|arg| arg.span).collect::>() + args.iter().map(|arg| tcx.hir().span(arg.hir_id)).collect::>() }; let mut err = tcx.sess.struct_span_err_with_code( @@ -196,7 +203,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } if sugg_unit { - let sugg_span = tcx.sess.source_map().end_point(expr.span); + let sugg_span = tcx.sess.source_map().end_point(tcx.hir().span(expr.hir_id)); // remove closing `)` from the span let sugg_span = sugg_span.shrink_to_lo(); err.span_suggestion( @@ -325,7 +332,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Closure arguments themselves can't be diverging, but // a previous argument can, e.g., `foo(panic!(), || {})`. if !check_closures { - self.warn_if_unreachable(arg.hir_id, arg.span, "expression"); + self.warn_if_unreachable(arg.hir_id, tcx.hir().span(arg.hir_id), "expression"); } let is_closure = matches!(arg.kind, ExprKind::Closure(..)); @@ -354,7 +361,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // 3. Relate the expected type and the formal one, // if the expected type was used for the coercion. - self.demand_suptype(arg.span, formal_ty, coerce_ty); + self.demand_suptype(tcx.hir().span(arg.hir_id), formal_ty, coerce_ty); } } @@ -369,24 +376,25 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for arg in args.iter().skip(expected_arg_count) { let arg_ty = self.check_expr(&arg); + let arg_span = tcx.hir().span(arg.hir_id); // There are a few types which get autopromoted when passed via varargs // in C but we just error out instead and require explicit casts. - let arg_ty = self.structurally_resolved_type(arg.span, arg_ty); + let arg_ty = self.structurally_resolved_type(arg_span, arg_ty); match arg_ty.kind() { ty::Float(ty::FloatTy::F32) => { - variadic_error(tcx.sess, arg.span, arg_ty, "c_double"); + variadic_error(tcx.sess, arg_span, arg_ty, "c_double"); } ty::Int(ty::IntTy::I8 | ty::IntTy::I16) | ty::Bool => { - variadic_error(tcx.sess, arg.span, arg_ty, "c_int"); + variadic_error(tcx.sess, arg_span, arg_ty, "c_int"); } ty::Uint(ty::UintTy::U8 | ty::UintTy::U16) => { - variadic_error(tcx.sess, arg.span, arg_ty, "c_uint"); + variadic_error(tcx.sess, arg_span, arg_ty, "c_uint"); } ty::FnDef(..) => { let ptr_ty = self.tcx.mk_fn_ptr(arg_ty.fn_sig(self.tcx)); let ptr_ty = self.resolve_vars_if_possible(ptr_ty); - variadic_error(tcx.sess, arg.span, arg_ty, &ptr_ty.to_string()); + variadic_error(tcx.sess, arg_span, arg_ty, &ptr_ty.to_string()); } _ => {} } @@ -498,7 +506,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // See #44848. let ref_bindings = local.pat.contains_explicit_ref_binding(); - let local_ty = self.local_ty(init.span, local.hir_id).revealed_ty; + let init_span = self.tcx.hir().span(init.hir_id); + let local_ty = self.local_ty(init_span, local.hir_id).revealed_ty; if let Some(m) = ref_bindings { // Somewhat subtle: if we have a `ref` binding in the pattern, // we want to avoid introducing coercions for the RHS. This is @@ -509,7 +518,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // type of the place it is referencing, and not some // supertype thereof. let init_ty = self.check_expr_with_needs(init, Needs::maybe_mut_place(m)); - self.demand_eqtype(init.span, local_ty, init_ty); + self.demand_eqtype(init_span, local_ty, init_ty); init_ty } else { self.check_expr_coercable_to_type(init, local_ty, None) @@ -532,7 +541,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Does the expected pattern type originate from an expression and what is the span? let (origin_expr, ty_span) = match (local.ty, local.init) { (Some(ty), _) => (false, Some(self.tcx.hir().span(ty.hir_id))), // Bias towards the explicit user type. - (_, Some(init)) => (true, Some(init.span)), // No explicit type; so use the scrutinee. + (_, Some(init)) => (true, Some(self.tcx.hir().span(init.hir_id))), // No explicit type; so use the scrutinee. _ => (false, None), // We have `let $pat;`, so the expected type is unconstrained. }; @@ -566,7 +575,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Check with expected type of `()`. self.check_expr_has_type_or_error(&expr, self.tcx.mk_unit(), |err| { if expr.can_have_side_effects() { - self.suggest_semicolon_at_end(expr.span, err); + self.suggest_semicolon_at_end(self.tcx.hir().span(expr.hir_id), err); } }); } @@ -853,7 +862,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - expr.span + self.tcx.hir().span(expr.hir_id) } fn overwrite_local_ty_if_err( @@ -968,7 +977,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let (Some(ref_in), None) = (referenced_in.pop(), referenced_in.pop()) { // We make sure that only *one* argument matches the obligation failure // and we assign the obligation's span to its expression's. - error.obligation.cause.make_mut().span = args[ref_in].span; + error.obligation.cause.make_mut().span = + self.tcx.hir().span(args[ref_in].hir_id); error.points_at_arg_span = true; } } diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs b/compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs index 8967a9e4221a4..ace7eae65a4bc 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs @@ -80,8 +80,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => return false, }; - let sig = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, sig).0; - let sig = self.normalize_associated_types_in(expr.span, sig); + let expr_span = hir.span(expr.hir_id); + let sig = self.replace_bound_vars_with_fresh_vars(expr_span, infer::FnCall, sig).0; + let sig = self.normalize_associated_types_in(expr_span, sig); if self.can_coerce(sig.output(), expected) { let (mut sugg_call, applicability) = if sig.inputs().is_empty() { (String::new(), Applicability::MachineApplicable) @@ -117,10 +118,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } Some(Node::Expr(hir::Expr { kind: ExprKind::Closure(_, _, body_id, _, _), - span: full_closure_span, + hir_id: full_closure_id, .. })) => { - if *full_closure_span == expr.span { + if hir.span(*full_closure_id) == expr_span { return false; } msg = "call this closure"; @@ -186,7 +187,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => {} } err.span_suggestion_verbose( - expr.span.shrink_to_hi(), + expr_span.shrink_to_hi(), &format!("use parentheses to {}", msg), format!("({})", sugg_call), applicability, @@ -214,10 +215,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.span_label(sp, &format!("{} defined here", found)); } } else if !self.check_for_cast(err, expr, found, expected, expected_ty_expr) { + let expr_span = self.tcx.hir().span(expr.hir_id); let is_struct_pat_shorthand_field = - self.is_hir_id_from_struct_pattern_shorthand_field(expr.hir_id, expr.span); - let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id); - if let Ok(expr_text) = self.sess().source_map().span_to_snippet(expr.span) { + self.is_hir_id_from_struct_pattern_shorthand_field(expr.hir_id, expr_span); + let methods = self.get_conversion_methods(expr_span, expected, found, expr.hir_id); + if let Ok(expr_text) = self.sess().source_map().span_to_snippet(expr_span) { let mut suggestions = iter::repeat(&expr_text) .zip(methods.iter()) .filter_map(|(receiver, method)| { @@ -248,7 +250,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .peekable(); if suggestions.peek().is_some() { err.span_suggestions( - expr.span, + expr_span, "try using a conversion method", suggestions, Applicability::MaybeIncorrect, @@ -275,12 +277,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return; } let boxed_found = self.tcx.mk_box(found); + let expr_span = self.tcx.hir().span(expr.hir_id); if let (true, Ok(snippet)) = ( self.can_coerce(boxed_found, expected), - self.sess().source_map().span_to_snippet(expr.span), + self.sess().source_map().span_to_snippet(expr_span), ) { err.span_suggestion( - expr.span, + expr_span, "store this in the heap by calling `Box::new`", format!("Box::new({})", snippet), Applicability::MachineApplicable, @@ -349,9 +352,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let boxed_found = self.tcx.mk_box(found); let new_found = self.tcx.mk_lang_item(boxed_found, LangItem::Pin).unwrap(); + let expr_span = self.tcx.hir().span(expr.hir_id); if let (true, Ok(snippet)) = ( self.can_coerce(new_found, expected), - self.sess().source_map().span_to_snippet(expr.span), + self.sess().source_map().span_to_snippet(expr_span), ) { match found.kind() { ty::Adt(def, _) if def.is_box() => { @@ -359,7 +363,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } _ => { err.span_suggestion( - expr.span, + expr_span, "you need to pin and box this expression", format!("Box::pin({})", snippet), Applicability::MachineApplicable, @@ -486,15 +490,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let found = self.resolve_vars_with_obligations(found); if let hir::FnRetTy::Return(ty) = fn_decl.output { + let expr_span = self.tcx.hir().span(expr.hir_id); let ty = AstConv::ast_ty_to_ty(self, ty); let ty = self.tcx.erase_late_bound_regions(Binder::bind(ty)); - let ty = self.normalize_associated_types_in(expr.span, ty); + let ty = self.normalize_associated_types_in(expr_span, ty); if self.can_coerce(found, ty) { err.multipart_suggestion( "you might have meant to return this value", vec![ - (expr.span.shrink_to_lo(), "return ".to_string()), - (expr.span.shrink_to_hi(), ";".to_string()), + (expr_span.shrink_to_lo(), "return ".to_string()), + (expr_span.shrink_to_hi(), ";".to_string()), ], Applicability::MaybeIncorrect, ); @@ -507,7 +512,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err: &mut DiagnosticBuilder<'_>, expr: &hir::Expr<'_>, ) { - let sp = self.tcx.sess.source_map().start_point(expr.span); + let expr_span = self.tcx.hir().span(expr.hir_id); + let sp = self.tcx.sess.source_map().start_point(expr_span); if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) { // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }` self.tcx.sess.parse_sess.expr_parentheses_needed(err, *sp, None); diff --git a/compiler/rustc_typeck/src/check/generator_interior.rs b/compiler/rustc_typeck/src/check/generator_interior.rs index ca971bef6a8a0..9f43d3da227fa 100644 --- a/compiler/rustc_typeck/src/check/generator_interior.rs +++ b/compiler/rustc_typeck/src/check/generator_interior.rs @@ -118,7 +118,7 @@ impl<'a, 'tcx> InteriorVisitor<'a, 'tcx> { "no type in expr = {:?}, count = {:?}, span = {:?}", expr, self.expr_count, - expr.map(|e| e.span) + expr.map(|e| self.fcx.tcx.hir().span(e.hir_id)) ); let ty = self.fcx.resolve_vars_if_possible(ty); if let Some((unresolved_type, unresolved_type_span)) = @@ -170,7 +170,7 @@ pub fn resolve_interior<'a, 'tcx>( // if a Sync generator contains an &'α T, we need to check whether &'α T: Sync), // so knowledge of the exact relationships between them isn't particularly important. - debug!("types in generator {:?}, span = {:?}", types, body.value.span); + debug!("types in generator {:?}, span = {:?}", types, fcx.tcx.hir().span(body.value.hir_id)); let mut counter = 0; let mut captured_tys = FxHashSet::default(); @@ -208,13 +208,14 @@ pub fn resolve_interior<'a, 'tcx>( visitor.fcx.inh.typeck_results.borrow_mut().generator_interior_types = ty::Binder::bind(type_causes); + let body_value_span = fcx.tcx.hir().span(body.value.hir_id); debug!( "types in generator after region replacement {:?}, span = {:?}", - witness, body.value.span + witness, body_value_span ); // Unify the type variable inside the generator with the new witness - match fcx.at(&fcx.misc(body.value.span), fcx.param_env).eq(interior, witness) { + match fcx.at(&fcx.misc(body_value_span), fcx.param_env).eq(interior, witness) { Ok(ok) => fcx.register_infer_ok_obligations(ok), _ => bug!(), } @@ -320,11 +321,12 @@ impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> { self.expr_count += 1; let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); + let expr_span = self.fcx.tcx.hir().span(expr.hir_id); // If there are adjustments, then record the final type -- // this is the actual value that is being produced. if let Some(adjusted_ty) = self.fcx.typeck_results.borrow().expr_ty_adjusted_opt(expr) { - self.record(adjusted_ty, scope, Some(expr), expr.span, guard_borrowing_from_pattern); + self.record(adjusted_ty, scope, Some(expr), expr_span, guard_borrowing_from_pattern); } // Also record the unadjusted type (which is the only type if @@ -362,11 +364,11 @@ impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> { tcx.mk_region(ty::RegionKind::ReErased), ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }, ); - self.record(ref_ty, scope, Some(expr), expr.span, guard_borrowing_from_pattern); + self.record(ref_ty, scope, Some(expr), expr_span, guard_borrowing_from_pattern); } - self.record(ty, scope, Some(expr), expr.span, guard_borrowing_from_pattern); + self.record(ty, scope, Some(expr), expr_span, guard_borrowing_from_pattern); } else { - self.fcx.tcx.sess.delay_span_bug(expr.span, "no type for node"); + self.fcx.tcx.sess.delay_span_bug(expr_span, "no type for node"); } } } diff --git a/compiler/rustc_typeck/src/check/method/confirm.rs b/compiler/rustc_typeck/src/check/method/confirm.rs index 7a80524f1b79a..f736d1b0bcce1 100644 --- a/compiler/rustc_typeck/src/check/method/confirm.rs +++ b/compiler/rustc_typeck/src/check/method/confirm.rs @@ -137,8 +137,11 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { ) -> Ty<'tcx> { // Commit the autoderefs by calling `autoderef` again, but this // time writing the results into the various typeck results. - let mut autoderef = - self.autoderef_overloaded_span(self.span, unadjusted_self_ty, self.call_expr.span); + let mut autoderef = self.autoderef_overloaded_span( + self.span, + unadjusted_self_ty, + self.tcx.hir().span(self.call_expr.hir_id), + ); let (_, n) = match autoderef.nth(pick.autoderefs) { Some(n) => n, None => { @@ -521,8 +524,8 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { ty::TraitContainer(trait_def_id) => callee::check_legal_trait_for_method_call( self.tcx, self.span, - Some(self.self_expr.span), - self.call_expr.span, + Some(self.tcx.hir().span(self.self_expr.hir_id)), + self.tcx.hir().span(self.call_expr.hir_id), trait_def_id, ), ty::ImplContainer(..) => {} diff --git a/compiler/rustc_typeck/src/check/method/mod.rs b/compiler/rustc_typeck/src/check/method/mod.rs index 9a3d1e42b732a..4827a0eb0b8ae 100644 --- a/compiler/rustc_typeck/src/check/method/mod.rs +++ b/compiler/rustc_typeck/src/check/method/mod.rs @@ -156,7 +156,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .unwrap_or(0); // Account for `foo.bar`; - let sugg_span = call_expr.span.shrink_to_hi(); + let sugg_span = self.tcx.hir().span(call_expr.hir_id).shrink_to_hi(); let (suggestion, applicability) = ( format!("({})", (0..params).map(|_| "_").collect::>().join(", ")), if params > 0 { Applicability::HasPlaceholders } else { Applicability::MaybeIncorrect }, diff --git a/compiler/rustc_typeck/src/check/method/suggest.rs b/compiler/rustc_typeck/src/check/method/suggest.rs index 77abba94eb3d1..23558f3c701a7 100644 --- a/compiler/rustc_typeck/src/check/method/suggest.rs +++ b/compiler/rustc_typeck/src/check/method/suggest.rs @@ -18,7 +18,7 @@ use rustc_middle::ty::{ }; use rustc_span::lev_distance; use rustc_span::symbol::{kw, sym, Ident}; -use rustc_span::{source_map, FileName, Span}; +use rustc_span::{FileName, Span}; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use rustc_trait_selection::traits::Obligation; @@ -180,7 +180,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { item.def_id, sugg_span, idx, - self.tcx.sess.source_map(), + self.tcx, ); } } @@ -222,7 +222,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { item.def_id, sugg_span, idx, - self.tcx.sess.source_map(), + self.tcx, ); } } @@ -234,7 +234,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let sugg_span = if let SelfSource::MethodCall(expr) = source { // Given `foo.bar(baz)`, `expr` is `bar`, but we want to point to the whole thing. - self.tcx.hir().expect_expr(self.tcx.hir().get_parent_node(expr.hir_id)).span + let hir = self.tcx.hir(); + hir.span(hir.expect_expr(hir.get_parent_node(expr.hir_id)).hir_id) } else { span }; @@ -477,7 +478,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if is_accessible { if self.is_fn_ty(&field_ty, span) { - let expr_span = expr.span.to(item_name.span); + let expr_span = self.tcx.hir().span(expr.hir_id); + let expr_span = expr_span.to(item_name.span); err.multipart_suggestion( &format!( "to call the function stored in `{}`, \ @@ -495,8 +497,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .tcx .hir() .expect_expr(self.tcx.hir().get_parent_node(expr.hir_id)); + let call_expr_span = self.tcx.hir().span(call_expr.hir_id); - if let Some(span) = call_expr.span.trim_start(item_name.span) { + if let Some(span) = call_expr_span.trim_start(item_name.span) { err.span_suggestion( span, "remove the arguments", @@ -527,7 +530,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } if let SelfSource::MethodCall(expr) = source { - if let Ok(expr_string) = tcx.sess.source_map().span_to_snippet(expr.span) { + let expr_span = tcx.hir().span(expr.hir_id); + if let Ok(expr_string) = tcx.sess.source_map().span_to_snippet(expr_span) { report_function(&mut err, expr_string); } else if let ExprKind::Path(QPath::Resolved(_, ref path)) = expr.kind { if let Some(segment) = path.segments.last() { @@ -563,8 +567,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.ty_to_value_string(actual.peel_refs()) }; if let SelfSource::MethodCall(expr) = source { + let expr_span = tcx.hir().span(expr.hir_id); err.span_suggestion( - expr.span.to(span), + expr_span.to(span), "use associated function syntax instead", format!("{}::{}", ty_str, item_name), Applicability::MachineApplicable, @@ -779,7 +784,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let SelfSource::MethodCall(expr) = source { let call_expr = self.tcx.hir().expect_expr(self.tcx.hir().get_parent_node(expr.hir_id)); - if let Some(span) = call_expr.span.trim_start(expr.span) { + let expr_span = tcx.hir().span(expr.hir_id); + let call_expr_span = tcx.hir().span(call_expr.hir_id); + if let Some(span) = call_expr_span.trim_start(expr_span) { err.span_suggestion( span, msg, @@ -1503,7 +1510,7 @@ fn print_disambiguation_help( def_id: DefId, span: Span, candidate: Option, - source_map: &source_map::SourceMap, + tcx: TyCtxt<'_>, ) { let mut applicability = Applicability::MachineApplicable; let sugg_args = if let (ty::AssocKind::Fn, Some(args)) = (kind, args) { @@ -1515,10 +1522,14 @@ fn print_disambiguation_help( "" }, args.iter() - .map(|arg| source_map.span_to_snippet(arg.span).unwrap_or_else(|_| { - applicability = Applicability::HasPlaceholders; - "_".to_owned() - })) + .map(|arg| tcx + .sess + .source_map() + .span_to_snippet(tcx.hir().span(arg.hir_id)) + .unwrap_or_else(|_| { + applicability = Applicability::HasPlaceholders; + "_".to_owned() + })) .collect::>() .join(", "), ) diff --git a/compiler/rustc_typeck/src/check/mod.rs b/compiler/rustc_typeck/src/check/mod.rs index d577f5f9a1a1c..4781bc5e09048 100644 --- a/compiler/rustc_typeck/src/check/mod.rs +++ b/compiler/rustc_typeck/src/check/mod.rs @@ -513,7 +513,7 @@ fn typeck_with_fallback<'tcx>( // Compute the fty from point of view of inside the fn. let fn_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), fn_sig); let fn_sig = inh.normalize_associated_types_in( - body.value.span, + tcx.hir().span(body.value.hir_id), body_id.hir_id, param_env, fn_sig, @@ -545,11 +545,12 @@ fn typeck_with_fallback<'tcx>( _ => fallback(), }); - let expected_type = fcx.normalize_associated_types_in(body.value.span, expected_type); - fcx.require_type_is_sized(expected_type, body.value.span, traits::ConstSized); + let body_value_span = tcx.hir().span(body.value.hir_id); + let expected_type = fcx.normalize_associated_types_in(body_value_span, expected_type); + fcx.require_type_is_sized(expected_type, body_value_span, traits::ConstSized); let revealed_ty = if tcx.features().impl_trait_in_bindings { - fcx.instantiate_opaque_types_from_value(id, expected_type, body.value.span) + fcx.instantiate_opaque_types_from_value(id, expected_type, body_value_span) } else { expected_type }; @@ -722,7 +723,7 @@ fn binding_opaque_type_cycle_error( tcx.typeck(tcx.hir().local_def_id(tcx.hir().get_parent_item(hir_id))); if let Some(ty) = typeck_results.node_type_opt(expr.hir_id) { err.span_label( - expr.span, + tcx.hir().span(expr.hir_id), &format!( "this is of type `{}`, which doesn't constrain \ `{}` enough to arrive to a concrete type", diff --git a/compiler/rustc_typeck/src/check/op.rs b/compiler/rustc_typeck/src/check/op.rs index 567cb1a90d0d9..a682b8fdfb7c4 100644 --- a/compiler/rustc_typeck/src/check/op.rs +++ b/compiler/rustc_typeck/src/check/op.rs @@ -35,7 +35,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ty = if !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() && is_builtin_binop(lhs_ty, rhs_ty, op) { - self.enforce_builtin_binop_types(&lhs.span, lhs_ty, &rhs.span, rhs_ty, op); + self.enforce_builtin_binop_types( + &self.tcx.hir().span(lhs.hir_id), + lhs_ty, + &self.tcx.hir().span(rhs.hir_id), + rhs_ty, + op, + ); self.tcx.mk_unit() } else { return_ty @@ -97,13 +103,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && is_builtin_binop(lhs_ty, rhs_ty, op) { let builtin_return_ty = self.enforce_builtin_binop_types( - &lhs_expr.span, + &self.tcx.hir().span(lhs_expr.hir_id), lhs_ty, - &rhs_expr.span, + &self.tcx.hir().span(rhs_expr.hir_id), rhs_ty, op, ); - self.demand_suptype(expr.span, builtin_return_ty, return_ty); + self.demand_suptype( + self.tcx.hir().span(expr.hir_id), + builtin_return_ty, + return_ty, + ); } return_ty @@ -175,7 +185,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let lhs_ty = self.check_expr(lhs_expr); let fresh_var = self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, - span: lhs_expr.span, + span: self.tcx.hir().span(lhs_expr.hir_id), }); self.demand_coerce(lhs_expr, lhs_ty, fresh_var, Some(rhs_expr), AllowTwoPhase::No) } @@ -197,7 +207,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // particularly for things like `String + &String`. let rhs_ty_var = self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, - span: rhs_expr.span, + span: self.tcx.hir().span(rhs_expr.hir_id), }); let result = self.lookup_op_method(lhs_ty, &[rhs_ty_var], Op::Binary(op, is_assign)); @@ -262,18 +272,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } Err(()) => { let source_map = self.tcx.sess.source_map(); + let lhs_span = self.tcx.hir().span(lhs_expr.hir_id); + let rhs_span = self.tcx.hir().span(rhs_expr.hir_id); let (mut err, missing_trait, use_output, involves_fn) = match is_assign { IsAssign::Yes => { let mut err = struct_span_err!( self.tcx.sess, - expr.span, + self.tcx.hir().span(expr.hir_id), E0368, "binary assignment operation `{}=` cannot be applied to type `{}`", op.node.as_str(), lhs_ty, ); err.span_label( - lhs_expr.span, + lhs_span, format!("cannot use `{}=` on type `{}`", op.node.as_str(), lhs_ty), ); let missing_trait = match op.node { @@ -377,22 +389,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut err = struct_span_err!(self.tcx.sess, op.span, E0369, "{}", message.as_str()); let mut involves_fn = false; - if !lhs_expr.span.eq(&rhs_expr.span) { + if !lhs_span.eq(&rhs_span) { involves_fn |= self.add_type_neq_err_label( - &mut err, - lhs_expr.span, - lhs_ty, - rhs_ty, - op, - is_assign, + &mut err, lhs_span, lhs_ty, rhs_ty, op, is_assign, ); involves_fn |= self.add_type_neq_err_label( - &mut err, - rhs_expr.span, - rhs_ty, - lhs_ty, - op, - is_assign, + &mut err, rhs_span, rhs_ty, lhs_ty, op, is_assign, ); } (err, missing_trait, use_output, involves_fn) @@ -401,12 +403,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut suggested_deref = false; if let Ref(_, rty, _) = lhs_ty.kind() { if { - self.infcx.type_is_copy_modulo_regions(self.param_env, rty, lhs_expr.span) + self.infcx.type_is_copy_modulo_regions(self.param_env, rty, lhs_span) && self .lookup_op_method(rty, &[rhs_ty], Op::Binary(op, is_assign)) .is_ok() } { - if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) { + if let Ok(lstring) = source_map.span_to_snippet(lhs_span) { let msg = &format!( "`{}{}` can be used on `{}`, you can dereference `{}`", op.node.as_str(), @@ -418,7 +420,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { lstring, ); err.span_suggestion_verbose( - lhs_expr.span.shrink_to_lo(), + lhs_span.shrink_to_lo(), msg, "*".to_string(), rustc_errors::Applicability::MachineApplicable, @@ -444,7 +446,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Check if the method would be found if the type param wasn't // involved. If so, it means that adding a trait bound to the param is // enough. Otherwise we do not give the suggestion. - let mut eraser = TypeParamEraser(&self, expr.span); + let mut eraser = + TypeParamEraser(&self, self.tcx.hir().span(expr.hir_id)); let needs_bound = self .lookup_op_method( eraser.fold_ty(lhs_ty), @@ -590,10 +593,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { op.span, "`+` cannot be used to concatenate two `&str` strings", ); - match source_map.span_to_snippet(lhs_expr.span) { + let lhs_expr_span = self.tcx.hir().span(lhs_expr.hir_id); + match source_map.span_to_snippet(lhs_expr_span) { Ok(lstring) => { err.span_suggestion( - lhs_expr.span, + lhs_expr_span, if lstring.starts_with('&') { remove_borrow_msg } else { @@ -617,13 +621,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (&Ref(_, l_ty, _), &Adt(..)) // Handle `&str` & `&String` + `String` if (*l_ty.kind() == Str || is_std_string(l_ty)) && is_std_string(rhs_ty) => { + let lhs_expr_span = self.tcx.hir().span(lhs_expr.hir_id); + let rhs_expr_span = self.tcx.hir().span(rhs_expr.hir_id); err.span_label( op.span, "`+` cannot be used to concatenate a `&str` with a `String`", ); match ( - source_map.span_to_snippet(lhs_expr.span), - source_map.span_to_snippet(rhs_expr.span), + source_map.span_to_snippet(lhs_expr_span), + source_map.span_to_snippet(rhs_expr_span), is_assign, ) { (Ok(l), Ok(r), IsAssign::No) => { @@ -637,8 +643,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.multipart_suggestion( msg, vec![ - (lhs_expr.span, to_string), - (rhs_expr.span, format!("&{}", r)), + (lhs_expr_span, to_string), + (rhs_expr_span, format!("&{}", r)), ], Applicability::MachineApplicable, ); @@ -660,7 +666,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { op: hir::UnOp, ) -> Ty<'tcx> { assert!(op.is_by_value()); - match self.lookup_op_method(operand_ty, &[], Op::Unary(op, ex.span)) { + let ex_span = self.tcx.hir().span(ex.hir_id); + match self.lookup_op_method(operand_ty, &[], Op::Unary(op, ex_span)) { Ok(method) => { self.write_method_call(ex.hir_id, method); method.sig.output() @@ -670,14 +677,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if !actual.references_error() { let mut err = struct_span_err!( self.tcx.sess, - ex.span, + ex_span, E0600, "cannot apply unary operator `{}` to type `{}`", op.as_str(), actual ); err.span_label( - ex.span, + ex_span, format!("cannot apply unary operator `{}`", op.as_str()), ); match actual.kind() { @@ -697,7 +704,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) = ex.kind { err.span_suggestion( - ex.span, + self.tcx.hir().span(ex.hir_id), &format!( "you may have meant the maximum value of `{}`", actual diff --git a/compiler/rustc_typeck/src/check/pat.rs b/compiler/rustc_typeck/src/check/pat.rs index c7662be60001a..e8c4eb89f74fd 100644 --- a/compiler/rustc_typeck/src/check/pat.rs +++ b/compiler/rustc_typeck/src/check/pat.rs @@ -449,9 +449,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None => (None, None), Some(expr) => { let ty = self.check_expr(expr); + let expr_span = self.tcx.hir().span(expr.hir_id); // Check that the end-point is of numeric or char type. let fail = !(ty.is_numeric() || ty.is_char() || ty.references_error()); - (Some(ty), Some((fail, ty, expr.span))) + (Some(ty), Some((fail, ty, expr_span))) } }; let (lhs_ty, lhs) = calc_side(lhs); diff --git a/compiler/rustc_typeck/src/check/place_op.rs b/compiler/rustc_typeck/src/check/place_op.rs index 254e41706f90b..3f82b0af74d0f 100644 --- a/compiler/rustc_typeck/src/check/place_op.rs +++ b/compiler/rustc_typeck/src/check/place_op.rs @@ -23,7 +23,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return Some(mt.ty); } - let ok = self.try_overloaded_deref(expr.span, oprnd_ty)?; + let expr_span = self.tcx.hir().span(expr.hir_id); + let ok = self.try_overloaded_deref(expr_span, oprnd_ty)?; let method = self.register_infer_ok_obligations(ok); if let ty::Ref(region, _, hir::Mutability::Not) = method.sig.inputs()[0].kind() { self.apply_adjustments( @@ -34,7 +35,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }], ); } else { - span_bug!(expr.span, "input to deref is not a ref?"); + span_bug!(expr_span, "input to deref is not a ref?"); } let ty = self.make_overloaded_place_return_type(method).ty; self.write_method_call(expr.hir_id, method); @@ -53,7 +54,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // autoderef that normal method probing does. They could likely be // consolidated. - let mut autoderef = self.autoderef(base_expr.span, base_ty); + let base_expr_span = self.tcx.hir().span(base_expr.hir_id); + let mut autoderef = self.autoderef(base_expr_span, base_ty); let mut result = None; while result.is_none() && autoderef.next().is_some() { result = self.try_index_step(expr, base_expr, &autoderef, idx_ty); @@ -96,12 +98,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // If some lookup succeeds, write callee into table and extract index/element // type from the method signature. // If some lookup succeeded, install method in table + let expr_span = self.tcx.hir().span(expr.hir_id); + let base_expr_span = self.tcx.hir().span(base_expr.hir_id); let input_ty = self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::AutoDeref, - span: base_expr.span, + span: base_expr_span, }); let method = - self.try_overloaded_place_op(expr.span, self_ty, &[input_ty], PlaceOp::Index); + self.try_overloaded_place_op(expr_span, self_ty, &[input_ty], PlaceOp::Index); let result = method.map(|ok| { debug!("try_index_step: success, using overloaded indexing"); @@ -117,7 +121,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ), }); } else { - span_bug!(expr.span, "input to index is not a ref?"); + span_bug!(expr_span, "input to index is not a ref?"); } if unsize { adjustments.push(Adjustment { @@ -234,8 +238,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Some(mut adjustments) = previous_adjustments { for adjustment in &mut adjustments { if let Adjust::Deref(Some(ref mut deref)) = adjustment.kind { + let expr_span = self.tcx.hir().span(expr.hir_id); if let Some(ok) = self.try_mutable_overloaded_place_op( - expr.span, + expr_span, source, &[], PlaceOp::Deref, @@ -250,7 +255,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && source.ty_adt_def().map_or(false, |adt| adt.is_manually_drop()) { let mut err = self.tcx.sess.struct_span_err( - expr.span, + expr_span, "not automatically applying `DerefMut` on `ManuallyDrop` union field", ); err.help( @@ -318,7 +323,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Some(ref ty) => slice::from_ref(ty), }; - let method = self.try_mutable_overloaded_place_op(expr.span, base_ty, arg_tys, op); + let expr_span = self.tcx.hir().span(expr.hir_id); + let method = self.try_mutable_overloaded_place_op(expr_span, base_ty, arg_tys, op); let method = match method { Some(ok) => self.register_infer_ok_obligations(ok), // Couldn't find the mutable variant of the place op, keep the @@ -331,7 +337,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let region = if let ty::Ref(r, _, hir::Mutability::Mut) = method.sig.inputs()[0].kind() { r } else { - span_bug!(expr.span, "input to mutable place op is not a mut ref?"); + span_bug!(expr_span, "input to mutable place op is not a mut ref?"); }; // Convert the autoref in the base expr to mutable with the correct diff --git a/compiler/rustc_typeck/src/check/regionck.rs b/compiler/rustc_typeck/src/check/regionck.rs index f2e807a4aa507..85df5a77bbf1f 100644 --- a/compiler/rustc_typeck/src/check/regionck.rs +++ b/compiler/rustc_typeck/src/check/regionck.rs @@ -392,15 +392,16 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> { fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { // Check any autoderefs or autorefs that appear. let cmt_result = self.constrain_adjustments(expr); + let expr_span = self.tcx.hir().span(expr.hir_id); // If necessary, constrain destructors in this expression. This will be // the adjusted form if there is an adjustment. match cmt_result { Ok(head_cmt) => { - self.check_safety_of_rvalue_destructor_if_necessary(&head_cmt, expr.span); + self.check_safety_of_rvalue_destructor_if_necessary(&head_cmt, expr_span); } Err(..) => { - self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd"); + self.tcx.sess.delay_span_bug(expr_span, "cat_expr Errd"); } } @@ -453,17 +454,18 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { } debug!("constrain_adjustments: adjustments={:?}", adjustments); + let expr_span = self.fcx.tcx.hir().span(expr.hir_id); // If necessary, constrain destructors in the unadjusted form of this // expression. - self.check_safety_of_rvalue_destructor_if_necessary(&place, expr.span); + self.check_safety_of_rvalue_destructor_if_necessary(&place, expr_span); for adjustment in adjustments { debug!("constrain_adjustments: adjustment={:?}, place={:?}", adjustment, place); if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind { self.link_region( - expr.span, + expr_span, deref.region, ty::BorrowKind::from_mutbl(deref.mutbl), &place, @@ -527,7 +529,8 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { debug!("link_addr_of: cmt={:?}", cmt); - self.link_region_from_node_type(expr.span, expr.hir_id, mutability, &cmt); + let expr_span = self.fcx.tcx.hir().span(expr.hir_id); + self.link_region_from_node_type(expr_span, expr.hir_id, mutability, &cmt); } /// Computes the guarantors for any ref bindings in a `let` and @@ -601,7 +604,8 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { match *autoref { adjustment::AutoBorrow::Ref(r, m) => { - self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m.into()), expr_cmt); + let expr_span = self.fcx.tcx.hir().span(expr.hir_id); + self.link_region(expr_span, r, ty::BorrowKind::from_mutbl(m.into()), expr_cmt); } adjustment::AutoBorrow::RawPtr(_) => {} diff --git a/compiler/rustc_typeck/src/check/upvar.rs b/compiler/rustc_typeck/src/check/upvar.rs index 254f12b956304..6d2b50110ad12 100644 --- a/compiler/rustc_typeck/src/check/upvar.rs +++ b/compiler/rustc_typeck/src/check/upvar.rs @@ -90,7 +90,8 @@ impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> { if let hir::ExprKind::Closure(cc, _, body_id, _, _) = expr.kind { let body = self.fcx.tcx.hir().body(body_id); self.visit_body(body); - self.fcx.analyze_closure(expr.hir_id, expr.span, body, cc); + let expr_span = self.fcx.tcx.hir().span(expr.hir_id); + self.fcx.analyze_closure(expr.hir_id, expr_span, body, cc); } intravisit::walk_expr(self, expr); diff --git a/compiler/rustc_typeck/src/check/writeback.rs b/compiler/rustc_typeck/src/check/writeback.rs index 5148289c573ea..c8f4dcb14210d 100644 --- a/compiler/rustc_typeck/src/check/writeback.rs +++ b/compiler/rustc_typeck/src/check/writeback.rs @@ -48,10 +48,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let span = self.tcx.hir().span(param.pat.hir_id); wbcx.visit_node_id(span, param.hir_id); } + + let body_value_span = self.tcx.hir().span(body.value.hir_id); + // Type only exists for constants and statics, not functions. match self.tcx.hir().body_owner_kind(item_id) { hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => { - wbcx.visit_node_id(body.value.span, item_id); + wbcx.visit_node_id(body_value_span, item_id); } hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => (), } @@ -61,7 +64,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { wbcx.visit_closures(); wbcx.visit_liberated_fn_sigs(); wbcx.visit_fru_field_types(); - wbcx.visit_opaque_types(body.value.span); + wbcx.visit_opaque_types(body_value_span); wbcx.visit_coercion_casts(); wbcx.visit_user_provided_tys(); wbcx.visit_user_provided_sigs(); @@ -203,7 +206,10 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { // When encountering `return [0][0]` outside of a `fn` body we can encounter a base // that isn't in the type table. We assume more relevant errors have already been // emitted, so we delay an ICE if none have. (#64638) - self.tcx().sess.delay_span_bug(e.span, &format!("bad base: `{:?}`", base)); + self.tcx().sess.delay_span_bug( + self.tcx().hir().span(e.hir_id), + &format!("bad base: `{:?}`", base), + ); } if let Some(ty::Ref(_, base_ty, _)) = base_ty { let index_ty = typeck_results.expr_ty_adjusted_opt(&index).unwrap_or_else(|| { @@ -212,7 +218,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { // already have been emitted, so we only gate on this with an ICE if no // error has been emitted. (#64638) self.fcx.tcx.ty_error_with_message( - e.span, + self.tcx().hir().span(e.hir_id), &format!("bad index {:?} for base: `{:?}`", index, base), ) }); @@ -263,13 +269,14 @@ impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { self.fix_scalar_builtin_expr(e); self.fix_index_builtin_expr(e); - self.visit_node_id(e.span, e.hir_id); + let e_span = self.fcx.tcx.hir().span(e.hir_id); + self.visit_node_id(e_span, e.hir_id); match e.kind { hir::ExprKind::Closure(_, _, body, _, _) => { let body = self.fcx.tcx.hir().body(body); for param in body.params { - self.visit_node_id(e.span, param.hir_id); + self.visit_node_id(e_span, param.hir_id); } self.visit_body(body); diff --git a/compiler/rustc_typeck/src/expr_use_visitor.rs b/compiler/rustc_typeck/src/expr_use_visitor.rs index f1163427de2dd..4cd7efcc9f3ad 100644 --- a/compiler/rustc_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_typeck/src/expr_use_visitor.rs @@ -441,7 +441,10 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { // may not. This will generate an error earlier in typeck, // so we can just ignore it. if !self.tcx().sess.has_errors() { - span_bug!(with_expr.span, "with expression doesn't evaluate to a struct"); + span_bug!( + self.tcx().hir().span(with_expr.hir_id), + "with expression doesn't evaluate to a struct" + ); } } } diff --git a/compiler/rustc_typeck/src/mem_categorization.rs b/compiler/rustc_typeck/src/mem_categorization.rs index b95d671fdc666..6d0d812cc76ca 100644 --- a/compiler/rustc_typeck/src/mem_categorization.rs +++ b/compiler/rustc_typeck/src/mem_categorization.rs @@ -268,6 +268,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { { debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr); let target = self.resolve_vars_if_possible(adjustment.target); + let expr_span = self.tcx().hir().span(expr.hir_id); match adjustment.kind { adjustment::Adjust::Deref(overloaded) => { // Equivalent to *expr or something similar. @@ -275,7 +276,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { let ref_ty = self .tcx() .mk_ref(deref.region, ty::TypeAndMut { ty: target, mutbl: deref.mutbl }); - self.cat_rvalue(expr.hir_id, expr.span, ref_ty) + self.cat_rvalue(expr.hir_id, expr_span, ref_ty) } else { previous()? }; @@ -286,7 +287,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { | adjustment::Adjust::Pointer(_) | adjustment::Adjust::Borrow(_) => { // Result is an rvalue. - Ok(self.cat_rvalue(expr.hir_id, expr.span, target)) + Ok(self.cat_rvalue(expr.hir_id, expr_span, target)) } } } @@ -340,7 +341,8 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { hir::ExprKind::Path(ref qpath) => { let res = self.typeck_results.qpath_res(qpath, expr.hir_id); - self.cat_res(expr.hir_id, expr.span, expr_ty, res) + let expr_span = self.tcx().hir().span(expr.hir_id); + self.cat_res(expr.hir_id, expr_span, expr_ty, res) } hir::ExprKind::Type(ref e, _) => self.cat_expr(&e), @@ -372,7 +374,9 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { | hir::ExprKind::InlineAsm(..) | hir::ExprKind::LlvmInlineAsm(..) | hir::ExprKind::Box(..) - | hir::ExprKind::Err => Ok(self.cat_rvalue(expr.hir_id, expr.span, expr_ty)), + | hir::ExprKind::Err => { + Ok(self.cat_rvalue(expr.hir_id, self.tcx().hir().span(expr.hir_id), expr_ty)) + } } } @@ -476,14 +480,15 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`. let place_ty = self.expr_ty(expr)?; let base_ty = self.expr_ty_adjusted(base)?; + let expr_span = self.tcx().hir().span(expr.hir_id); let (region, mutbl) = match *base_ty.kind() { ty::Ref(region, _, mutbl) => (region, mutbl), - _ => span_bug!(expr.span, "cat_overloaded_place: base is not a reference"), + _ => span_bug!(expr_span, "cat_overloaded_place: base is not a reference"), }; let ref_ty = self.tcx().mk_ref(region, ty::TypeAndMut { ty: place_ty, mutbl }); - let base = self.cat_rvalue(expr.hir_id, expr.span, ref_ty); + let base = self.cat_rvalue(expr.hir_id, expr_span, ref_ty); self.cat_deref(expr, base) } diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 8b5f5b66c45fc..b63ad6c820c48 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -391,9 +391,10 @@ crate fn is_literal_expr(cx: &DocContext<'_>, hir_id: hir::HirId) -> bool { crate fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String { let hir = tcx.hir(); let value = &hir.body(body).value; + let value_span = hir.span(value.hir_id); - let snippet = if !value.span.from_expansion() { - tcx.sess.source_map().span_to_snippet(value.span).ok() + let snippet = if !value_span.from_expansion() { + tcx.sess.source_map().span_to_snippet(value_span).ok() } else { None }; diff --git a/src/tools/clippy/clippy_lints/src/approx_const.rs b/src/tools/clippy/clippy_lints/src/approx_const.rs index 1d511a86c9099..d5451f409bb52 100644 --- a/src/tools/clippy/clippy_lints/src/approx_const.rs +++ b/src/tools/clippy/clippy_lints/src/approx_const.rs @@ -87,7 +87,7 @@ fn check_known_consts(cx: &LateContext<'_>, e: &Expr<'_>, s: symbol::Symbol, mod span_lint( cx, APPROX_CONSTANT, - e.span, + cx.tcx.hir().span(e.hir_id), &format!( "approximate value of `{}::consts::{}` found. \ Consider using it directly", diff --git a/src/tools/clippy/clippy_lints/src/arithmetic.rs b/src/tools/clippy/clippy_lints/src/arithmetic.rs index 61fdf9495b918..8a32cd6bf1b34 100644 --- a/src/tools/clippy/clippy_lints/src/arithmetic.rs +++ b/src/tools/clippy/clippy_lints/src/arithmetic.rs @@ -64,8 +64,9 @@ impl<'tcx> LateLintPass<'tcx> for Arithmetic { return; } + let expr_span = cx.tcx.hir().span(expr.hir_id); if let Some(span) = self.const_span { - if span.contains(expr.span) { + if span.contains(expr_span) { return; } } @@ -94,35 +95,36 @@ impl<'tcx> LateLintPass<'tcx> for Arithmetic { hir::ExprKind::Unary(hir::UnOp::Neg, expr) => { if let hir::ExprKind::Lit(lit) = &expr.kind { if let rustc_ast::ast::LitKind::Int(1, _) = lit.node { - span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected"); - self.expr_span = Some(expr.span); + let expr_span = cx.tcx.hir().span(expr.hir_id); + span_lint(cx, INTEGER_ARITHMETIC, expr_span, "integer arithmetic detected"); + self.expr_span = Some(expr_span); } } }, _ => { - span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected"); - self.expr_span = Some(expr.span); + span_lint(cx, INTEGER_ARITHMETIC, expr_span, "integer arithmetic detected"); + self.expr_span = Some(expr_span); }, }, _ => { - span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected"); - self.expr_span = Some(expr.span); + span_lint(cx, INTEGER_ARITHMETIC, expr_span, "integer arithmetic detected"); + self.expr_span = Some(expr_span); }, } } else if r_ty.peel_refs().is_floating_point() && r_ty.peel_refs().is_floating_point() { - span_lint(cx, FLOAT_ARITHMETIC, expr.span, "floating-point arithmetic detected"); - self.expr_span = Some(expr.span); + span_lint(cx, FLOAT_ARITHMETIC, expr_span, "floating-point arithmetic detected"); + self.expr_span = Some(expr_span); } }, hir::ExprKind::Unary(hir::UnOp::Neg, arg) => { let ty = cx.typeck_results().expr_ty(arg); if constant_simple(cx, cx.typeck_results(), expr).is_none() { if ty.is_integral() { - span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected"); - self.expr_span = Some(expr.span); + span_lint(cx, INTEGER_ARITHMETIC, expr_span, "integer arithmetic detected"); + self.expr_span = Some(expr_span); } else if ty.is_floating_point() { - span_lint(cx, FLOAT_ARITHMETIC, expr.span, "floating-point arithmetic detected"); - self.expr_span = Some(expr.span); + span_lint(cx, FLOAT_ARITHMETIC, expr_span, "floating-point arithmetic detected"); + self.expr_span = Some(expr_span); } } }, @@ -130,8 +132,8 @@ impl<'tcx> LateLintPass<'tcx> for Arithmetic { } } - fn check_expr_post(&mut self, _: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { - if Some(expr.span) == self.expr_span { + fn check_expr_post(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { + if Some(cx.tcx.hir().span(expr.hir_id)) == self.expr_span { self.expr_span = None; } } diff --git a/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs b/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs index 77b26faaa586a..c2f7372f5622e 100644 --- a/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs +++ b/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs @@ -33,7 +33,7 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnConstants { span_lint_and_help( cx, ASSERTIONS_ON_CONSTANTS, - e.span, + cx.tcx.hir().span(e.hir_id), if is_debug { "`debug_assert!(true)` will be optimized out by the compiler" } else { @@ -47,7 +47,7 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnConstants { span_lint_and_help( cx, ASSERTIONS_ON_CONSTANTS, - e.span, + cx.tcx.hir().span(e.hir_id), "`assert!(false)` should probably be replaced", None, "use `panic!()` or `unreachable!()`", @@ -57,14 +57,14 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnConstants { span_lint_and_help( cx, ASSERTIONS_ON_CONSTANTS, - e.span, + cx.tcx.hir().span(e.hir_id), &format!("`assert!(false, {})` should probably be replaced", panic_message), None, &format!("use `panic!({})` or `unreachable!({})`", panic_message, panic_message), ) }; - if let Some(debug_assert_span) = is_expn_of(e.span, "debug_assert") { + if let Some(debug_assert_span) = is_expn_of(cx.tcx.hir().span(e.hir_id), "debug_assert") { if debug_assert_span.from_expansion() { return; } @@ -76,7 +76,7 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnConstants { lint_true(true); } }; - } else if let Some(assert_span) = is_direct_expn_of(e.span, "assert") { + } else if let Some(assert_span) = is_direct_expn_of(cx.tcx.hir().span(e.hir_id), "assert") { if assert_span.from_expansion() { return; } @@ -128,7 +128,7 @@ fn match_assert_with_message<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) if let Some(args) = match_panic_call(cx, begin_panic_call); if args.len() == 1; // bind the second argument of the `assert!` macro if it exists - if let panic_message = snippet_opt(cx, args[0].span); + if let panic_message = snippet_opt(cx, cx.tcx.hir().span(args[0].hir_id)); // second argument of begin_panic is irrelevant // as is the second match arm then { diff --git a/src/tools/clippy/clippy_lints/src/assign_ops.rs b/src/tools/clippy/clippy_lints/src/assign_ops.rs index e13f62d04281a..30b3f91c76cd9 100644 --- a/src/tools/clippy/clippy_lints/src/assign_ops.rs +++ b/src/tools/clippy/clippy_lints/src/assign_ops.rs @@ -133,14 +133,14 @@ impl<'tcx> LateLintPass<'tcx> for AssignOps { span_lint_and_then( cx, ASSIGN_OP_PATTERN, - expr.span, + cx.tcx.hir().span(expr.hir_id), "manual implementation of an assign operation", |diag| { if let (Some(snip_a), Some(snip_r)) = - (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span)) + (snippet_opt(cx, cx.tcx.hir().span(assignee.hir_id)), snippet_opt(cx, cx.tcx.hir().span(rhs.hir_id))) { diag.span_suggestion( - expr.span, + cx.tcx.hir().span(expr.hir_id), "replace it with", format!("{} {}= {}", snip_a, op.node.as_str(), snip_r), Applicability::MachineApplicable, @@ -199,15 +199,15 @@ fn lint_misrefactored_assign_op( span_lint_and_then( cx, MISREFACTORED_ASSIGN_OP, - expr.span, + cx.tcx.hir().span(expr.hir_id), "variable appears on both sides of an assignment operation", |diag| { - if let (Some(snip_a), Some(snip_r)) = (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span)) { + if let (Some(snip_a), Some(snip_r)) = (snippet_opt(cx, cx.tcx.hir().span(assignee.hir_id)), snippet_opt(cx, cx.tcx.hir().span(rhs_other.hir_id))) { let a = &sugg::Sugg::hir(cx, assignee, ".."); let r = &sugg::Sugg::hir(cx, rhs, ".."); let long = format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r)); diag.span_suggestion( - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!( "did you mean `{} = {} {} {}` or `{}`? Consider replacing it with", snip_a, @@ -220,7 +220,7 @@ fn lint_misrefactored_assign_op( Applicability::MaybeIncorrect, ); diag.span_suggestion( - expr.span, + cx.tcx.hir().span(expr.hir_id), "or", long, Applicability::MaybeIncorrect, // snippet diff --git a/src/tools/clippy/clippy_lints/src/async_yields_async.rs b/src/tools/clippy/clippy_lints/src/async_yields_async.rs index 869a5c28d0511..49545e1c1e015 100644 --- a/src/tools/clippy/clippy_lints/src/async_yields_async.rs +++ b/src/tools/clippy/clippy_lints/src/async_yields_async.rs @@ -56,7 +56,7 @@ impl<'tcx> LateLintPass<'tcx> for AsyncYieldsAsync { if implements_trait(cx, expr_ty, future_trait_def_id, &[]) { let return_expr_span = match &body.value.kind { // XXXkhuey there has to be a better way. - ExprKind::Block(block, _) => block.expr.map(|e| e.span), + ExprKind::Block(block, _) => block.expr.map(|e| cx.tcx.hir().span(e.hir_id)), ExprKind::Path(QPath::Resolved(_, path)) => Some(path.span), _ => None, }; @@ -67,7 +67,7 @@ impl<'tcx> LateLintPass<'tcx> for AsyncYieldsAsync { return_expr_span, "an async construct yields a type which is itself awaitable", |db| { - db.span_label(body.value.span, "outer async construct"); + db.span_label(cx.tcx.hir().span(body.value.hir_id), "outer async construct"); db.span_label(return_expr_span, "awaitable value not awaited"); db.span_suggestion( return_expr_span, diff --git a/src/tools/clippy/clippy_lints/src/atomic_ordering.rs b/src/tools/clippy/clippy_lints/src/atomic_ordering.rs index 703d8a6f62bb1..3cc09c6b1ca3a 100644 --- a/src/tools/clippy/clippy_lints/src/atomic_ordering.rs +++ b/src/tools/clippy/clippy_lints/src/atomic_ordering.rs @@ -97,7 +97,7 @@ fn check_atomic_load_store(cx: &LateContext<'_>, expr: &Expr<'_>) { span_lint_and_help( cx, INVALID_ATOMIC_ORDERING, - ordering_arg.span, + cx.tcx.hir().span(ordering_arg.hir_id), "atomic loads cannot have `Release` and `AcqRel` ordering", None, "consider using ordering modes `Acquire`, `SeqCst` or `Relaxed`" @@ -107,7 +107,7 @@ fn check_atomic_load_store(cx: &LateContext<'_>, expr: &Expr<'_>) { span_lint_and_help( cx, INVALID_ATOMIC_ORDERING, - ordering_arg.span, + cx.tcx.hir().span(ordering_arg.hir_id), "atomic stores cannot have `Acquire` and `AcqRel` ordering", None, "consider using ordering modes `Release`, `SeqCst` or `Relaxed`" @@ -132,7 +132,7 @@ fn check_memory_fence(cx: &LateContext<'_>, expr: &Expr<'_>) { span_lint_and_help( cx, INVALID_ATOMIC_ORDERING, - args[0].span, + cx.tcx.hir().span(args[0].hir_id), "memory fences cannot have `Relaxed` ordering", None, "consider using ordering modes `Acquire`, `Release`, `AcqRel` or `SeqCst`" @@ -192,7 +192,7 @@ fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) { span_lint_and_help( cx, INVALID_ATOMIC_ORDERING, - failure_order_arg.span, + cx.tcx.hir().span(failure_order_arg.hir_id), &format!( "{}'s failure ordering may not be `Release` or `AcqRel`", method, @@ -205,7 +205,7 @@ fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) { span_lint_and_help( cx, INVALID_ATOMIC_ORDERING, - failure_order_arg.span, + cx.tcx.hir().span(failure_order_arg.hir_id), &format!( "{}'s failure ordering may not be stronger than the success ordering of `{}`", method, diff --git a/src/tools/clippy/clippy_lints/src/await_holding_invalid.rs b/src/tools/clippy/clippy_lints/src/await_holding_invalid.rs index 14b6a156c621e..2c5565eb51c03 100644 --- a/src/tools/clippy/clippy_lints/src/await_holding_invalid.rs +++ b/src/tools/clippy/clippy_lints/src/await_holding_invalid.rs @@ -101,7 +101,7 @@ impl LateLintPass<'_> for AwaitHolding { check_interior_types( cx, &typeck_results.generator_interior_types.as_ref().skip_binder(), - body.value.span, + cx.tcx.hir().span(body.value.hir_id), ); } } diff --git a/src/tools/clippy/clippy_lints/src/bit_mask.rs b/src/tools/clippy/clippy_lints/src/bit_mask.rs index a4ee54076ee98..14d0d477ff57f 100644 --- a/src/tools/clippy/clippy_lints/src/bit_mask.rs +++ b/src/tools/clippy/clippy_lints/src/bit_mask.rs @@ -115,9 +115,9 @@ impl<'tcx> LateLintPass<'tcx> for BitMask { if let ExprKind::Binary(cmp, left, right) = &e.kind { if cmp.node.is_comparison() { if let Some(cmp_opt) = fetch_int_literal(cx, right) { - check_compare(cx, left, cmp.node, cmp_opt, e.span) + check_compare(cx, left, cmp.node, cmp_opt, cx.tcx.hir().span(e.hir_id)) } else if let Some(cmp_val) = fetch_int_literal(cx, left) { - check_compare(cx, right, invert_cmp(cmp.node), cmp_val, e.span) + check_compare(cx, right, invert_cmp(cmp.node), cmp_val, cx.tcx.hir().span(e.hir_id)) } } } @@ -135,12 +135,12 @@ impl<'tcx> LateLintPass<'tcx> for BitMask { then { span_lint_and_then(cx, VERBOSE_BIT_MASK, - e.span, + cx.tcx.hir().span(e.hir_id), "bit mask could be simplified with a call to `trailing_zeros`", |diag| { let sugg = Sugg::hir(cx, left1, "...").maybe_par(); diag.span_suggestion( - e.span, + cx.tcx.hir().span(e.hir_id), "try", format!("{}.trailing_zeros() >= {}", sugg, n.count_ones()), Applicability::MaybeIncorrect, 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 6bbd27b0c35e2..06c1e3393fc19 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 @@ -70,7 +70,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ExVisitor<'a, 'tcx> { let body = self.cx.tcx.hir().body(eid); let ex = &body.value; - if matches!(ex.kind, ExprKind::Block(_, _)) && !body.value.span.from_expansion() { + if matches!(ex.kind, ExprKind::Block(_, _)) && !self.cx.tcx.hir().span(body.value.hir_id).from_expansion() { self.found_block = Some(ex); return; } @@ -88,7 +88,8 @@ const COMPLEX_BLOCK_MESSAGE: &str = "in an `if` condition, avoid complex blocks impl<'tcx> LateLintPass<'tcx> for BlocksInIfConditions { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if in_external_macro(cx.sess(), expr.span) { + let expr_span = cx.tcx.hir().span(expr.hir_id); + if in_external_macro(cx.sess(), expr_span) { return; } if let ExprKind::If(cond, _, _) = &expr.kind { @@ -98,23 +99,23 @@ impl<'tcx> LateLintPass<'tcx> for BlocksInIfConditions { if let Some(ex) = &block.expr { // don't dig into the expression here, just suggest that they remove // the block - if expr.span.from_expansion() || differing_macro_contexts(expr.span, ex.span) { + if expr_span.from_expansion() || differing_macro_contexts(expr_span, cx.tcx.hir().span(ex.hir_id)) { return; } let mut applicability = Applicability::MachineApplicable; span_lint_and_sugg( cx, BLOCKS_IN_IF_CONDITIONS, - cond.span, + cx.tcx.hir().span(cond.hir_id), BRACED_EXPR_MESSAGE, "try", format!( "{}", snippet_block_with_applicability( cx, - ex.span, + cx.tcx.hir().span(ex.hir_id), "..", - Some(expr.span), + Some(expr_span), &mut applicability ) ), @@ -122,8 +123,8 @@ impl<'tcx> LateLintPass<'tcx> for BlocksInIfConditions { ); } } else { - 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) { + let span = block.expr.as_ref().map_or_else(|| cx.tcx.hir().span(block.stmts[0].hir_id), |e| cx.tcx.hir().span(e.hir_id)); + if span.from_expansion() || differing_macro_contexts(expr_span, span) { return; } // move block higher @@ -131,7 +132,7 @@ impl<'tcx> LateLintPass<'tcx> for BlocksInIfConditions { span_lint_and_sugg( cx, BLOCKS_IN_IF_CONDITIONS, - expr.span.with_hi(cond.span.hi()), + expr_span.with_hi(cx.tcx.hir().span(cond.hir_id).hi()), COMPLEX_BLOCK_MESSAGE, "try", format!( @@ -140,7 +141,7 @@ impl<'tcx> LateLintPass<'tcx> for BlocksInIfConditions { cx, cx.tcx.hir().span(block.hir_id), "..", - Some(expr.span), + Some(expr_span), &mut applicability ), ), @@ -152,7 +153,7 @@ impl<'tcx> LateLintPass<'tcx> for BlocksInIfConditions { let mut visitor = ExVisitor { found_block: None, cx }; walk_expr(&mut visitor, cond); if let Some(block) = visitor.found_block { - span_lint(cx, BLOCKS_IN_IF_CONDITIONS, block.span, COMPLEX_BLOCK_MESSAGE); + span_lint(cx, BLOCKS_IN_IF_CONDITIONS, cx.tcx.hir().span(block.hir_id), COMPLEX_BLOCK_MESSAGE); } } } diff --git a/src/tools/clippy/clippy_lints/src/booleans.rs b/src/tools/clippy/clippy_lints/src/booleans.rs index c26e0fb2a9bb6..146356c8d05a1 100644 --- a/src/tools/clippy/clippy_lints/src/booleans.rs +++ b/src/tools/clippy/clippy_lints/src/booleans.rs @@ -106,7 +106,7 @@ impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> { } // prevent folding of `cfg!` macros and the like - if !e.span.from_expansion() { + if !self.cx.tcx.hir().span(e.hir_id).from_expansion() { match &e.kind { ExprKind::Unary(UnOp::Not, inner) => return Ok(Bool::Not(box self.run(inner)?)), ExprKind::Binary(binop, lhs, rhs) => match &binop.node { @@ -185,7 +185,7 @@ impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> { self.output.push_str(&str) } else { self.output.push('!'); - let snip = snippet_opt(self.cx, terminal.span)?; + let snip = snippet_opt(self.cx, self.cx.tcx.hir().span(terminal.hir_id))?; self.output.push_str(&snip); } }, @@ -217,7 +217,7 @@ impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> { } }, &Term(n) => { - let snip = snippet_opt(self.cx, self.terminals[n as usize].span)?; + let snip = snippet_opt(self.cx, self.cx.tcx.hir().span(self.terminals[n as usize].hir_id))?; self.output.push_str(&snip); }, } @@ -244,9 +244,9 @@ fn simplify_not(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option { .and_then(|op| { Some(format!( "{}{}{}", - snippet_opt(cx, lhs.span)?, + snippet_opt(cx, cx.tcx.hir().span(lhs.hir_id))?, op, - snippet_opt(cx, rhs.span)? + snippet_opt(cx, cx.tcx.hir().span(rhs.hir_id))? )) }) }, @@ -265,7 +265,7 @@ fn simplify_not(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option { let path: &str = &path.ident.name.as_str(); a == path }) - .and_then(|(_, neg_method)| Some(format!("{}.{}()", snippet_opt(cx, args[0].span)?, neg_method))) + .and_then(|(_, neg_method)| Some(format!("{}.{}()", snippet_opt(cx, cx.tcx.hir().span(args[0].hir_id))?, neg_method))) }, _ => None, } @@ -377,16 +377,16 @@ impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> { span_lint_and_then( self.cx, LOGIC_BUG, - e.span, + self.cx.tcx.hir().span(e.hir_id), "this boolean expression contains a logic bug", |diag| { diag.span_help( - h2q.terminals[i].span, + self.cx.tcx.hir().span(h2q.terminals[i].hir_id), "this expression can be optimized out by applying boolean operations to the \ outer expression", ); diag.span_suggestion( - e.span, + self.cx.tcx.hir().span(e.hir_id), "it would look like the following", suggest(self.cx, suggestion, &h2q.terminals), // nonminimal_bool can produce minimal but @@ -412,11 +412,11 @@ impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> { span_lint_and_then( self.cx, NONMINIMAL_BOOL, - e.span, + self.cx.tcx.hir().span(e.hir_id), "this boolean expression can be simplified", |diag| { diag.span_suggestions( - e.span, + self.cx.tcx.hir().span(e.hir_id), "try", suggestions.into_iter(), // nonminimal_bool can produce minimal but @@ -445,7 +445,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> { type Map = Map<'tcx>; fn visit_expr(&mut self, e: &'tcx Expr<'_>) { - if in_macro(e.span) { + if in_macro(self.cx.tcx.hir().span(e.hir_id)) { return; } match &e.kind { @@ -485,7 +485,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NotSimplificationVisitor<'a, 'tcx> { span_lint_and_sugg( self.cx, NONMINIMAL_BOOL, - expr.span, + self.cx.tcx.hir().span(expr.hir_id), "this boolean expression can be simplified", "try", suggestion, diff --git a/src/tools/clippy/clippy_lints/src/bytecount.rs b/src/tools/clippy/clippy_lints/src/bytecount.rs index eb5dc7ceecdc7..fe75f022bda9e 100644 --- a/src/tools/clippy/clippy_lints/src/bytecount.rs +++ b/src/tools/clippy/clippy_lints/src/bytecount.rs @@ -80,12 +80,12 @@ impl<'tcx> LateLintPass<'tcx> for ByteCount { span_lint_and_sugg( cx, NAIVE_BYTECOUNT, - expr.span, + cx.tcx.hir().span(expr.hir_id), "you appear to be counting bytes the naive way", "consider using the bytecount crate", format!("bytecount::count({}, {})", - snippet_with_applicability(cx, haystack.span, "..", &mut applicability), - snippet_with_applicability(cx, needle.span, "..", &mut applicability)), + snippet_with_applicability(cx, cx.tcx.hir().span(haystack.hir_id), "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(needle.hir_id), "..", &mut applicability)), applicability, ); } diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_lossless.rs b/src/tools/clippy/clippy_lints/src/casts/cast_lossless.rs index 478832a5164a0..a4cf81fa3a8d5 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_lossless.rs +++ b/src/tools/clippy/clippy_lints/src/casts/cast_lossless.rs @@ -15,7 +15,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_op: &Expr<'_>, c // The suggestion is to use a function call, so if the original expression // has parens on the outside, they are no longer needed. let mut applicability = Applicability::MachineApplicable; - let opt = snippet_opt(cx, cast_op.span); + let opt = snippet_opt(cx, cx.tcx.hir().span(cast_op.hir_id)); let sugg = opt.as_ref().map_or_else( || { applicability = Applicability::HasPlaceholders; @@ -33,7 +33,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_op: &Expr<'_>, c span_lint_and_sugg( cx, CAST_LOSSLESS, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!( "casting `{}` to `{}` may become silently lossy if you later change the type", cast_from, cast_to diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_possible_truncation.rs b/src/tools/clippy/clippy_lints/src/casts/cast_possible_truncation.rs index 33b06b8fe7caf..7978baf25a571 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_possible_truncation.rs +++ b/src/tools/clippy/clippy_lints/src/casts/cast_possible_truncation.rs @@ -50,5 +50,5 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, ca }, }; - span_lint(cx, CAST_POSSIBLE_TRUNCATION, expr.span, &msg); + span_lint(cx, CAST_POSSIBLE_TRUNCATION, cx.tcx.hir().span(expr.hir_id), &msg); } diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_possible_wrap.rs b/src/tools/clippy/clippy_lints/src/casts/cast_possible_wrap.rs index 56d301ed3e1c5..5217333a3a7b9 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_possible_wrap.rs +++ b/src/tools/clippy/clippy_lints/src/casts/cast_possible_wrap.rs @@ -34,7 +34,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, ca span_lint( cx, CAST_POSSIBLE_WRAP, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!( "casting `{}` to `{}` may wrap around the value{}", cast_from, cast_to, suffix, diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_precision_loss.rs b/src/tools/clippy/clippy_lints/src/casts/cast_precision_loss.rs index a1c3900ce1f6c..6eb50b4671421 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_precision_loss.rs +++ b/src/tools/clippy/clippy_lints/src/casts/cast_precision_loss.rs @@ -37,7 +37,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, ca span_lint( cx, CAST_PRECISION_LOSS, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!( "casting `{0}` to `{1}` causes a loss of precision {2}(`{0}` is {3} bits wide, \ but `{1}`'s mantissa is only {4} bits wide)", diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs b/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs index 87fb5557be066..65fcc26082d7e 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs +++ b/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs @@ -51,7 +51,7 @@ fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, cast_f span_lint( cx, CAST_PTR_ALIGNMENT, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!( "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)", cast_from, diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_ref_to_mut.rs b/src/tools/clippy/clippy_lints/src/casts/cast_ref_to_mut.rs index 3fdc1c6168ba9..ab7540926d789 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_ref_to_mut.rs +++ b/src/tools/clippy/clippy_lints/src/casts/cast_ref_to_mut.rs @@ -20,7 +20,7 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { span_lint( cx, CAST_REF_TO_MUT, - expr.span, + cx.tcx.hir().span(expr.hir_id), "casting `&T` to `&mut T` may cause undefined behavior, consider instead using an `UnsafeCell`", ); } diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_sign_loss.rs b/src/tools/clippy/clippy_lints/src/casts/cast_sign_loss.rs index 9656fbebd7720..a3250d95ce962 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_sign_loss.rs +++ b/src/tools/clippy/clippy_lints/src/casts/cast_sign_loss.rs @@ -14,7 +14,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_op: &Expr<'_>, c span_lint( cx, CAST_SIGN_LOSS, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!( "casting `{}` to `{}` may lose the sign of the value", cast_from, cast_to @@ -48,7 +48,7 @@ fn should_lint(cx: &LateContext<'_>, cast_op: &Expr<'_>, cast_from: Ty<'_>, cast if_chain! { if method_name == "unwrap"; - if let Some(arglist) = method_chain_args(cast_op, &["unwrap"]); + if let Some(arglist) = method_chain_args(cx, cast_op, &["unwrap"]); if let ExprKind::MethodCall(ref inner_path, _, _, _) = &arglist[0][0].kind; then { method_name = inner_path.ident.name.as_str(); diff --git a/src/tools/clippy/clippy_lints/src/casts/char_lit_as_u8.rs b/src/tools/clippy/clippy_lints/src/casts/char_lit_as_u8.rs index ccaad1b8f2ac7..bacccbf751b75 100644 --- a/src/tools/clippy/clippy_lints/src/casts/char_lit_as_u8.rs +++ b/src/tools/clippy/clippy_lints/src/casts/char_lit_as_u8.rs @@ -18,19 +18,19 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(expr).kind(); then { let mut applicability = Applicability::MachineApplicable; - let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability); + let snippet = snippet_with_applicability(cx, cx.tcx.hir().span(e.hir_id), "'x'", &mut applicability); span_lint_and_then( cx, CHAR_LIT_AS_U8, - expr.span, + cx.tcx.hir().span(expr.hir_id), "casting a character literal to `u8` truncates", |diag| { diag.note("`char` is four bytes wide, but `u8` is a single byte"); if c.is_ascii() { diag.span_suggestion( - expr.span, + cx.tcx.hir().span(expr.hir_id), "use a byte literal instead", format!("b{}", snippet), applicability, diff --git a/src/tools/clippy/clippy_lints/src/casts/fn_to_numeric_cast.rs b/src/tools/clippy/clippy_lints/src/casts/fn_to_numeric_cast.rs index a8d508585b5d4..252afeda1b572 100644 --- a/src/tools/clippy/clippy_lints/src/casts/fn_to_numeric_cast.rs +++ b/src/tools/clippy/clippy_lints/src/casts/fn_to_numeric_cast.rs @@ -17,14 +17,15 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, match cast_from.kind() { ty::FnDef(..) | ty::FnPtr(_) => { let mut applicability = Applicability::MaybeIncorrect; - let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability); + let from_snippet = + snippet_with_applicability(cx, cx.tcx.hir().span(cast_expr.hir_id), "x", &mut applicability); let to_nbits = utils::int_ty_to_nbits(cast_to, cx.tcx); if (to_nbits >= cx.tcx.data_layout.pointer_size.bits()) && (*cast_to.kind() != ty::Uint(UintTy::Usize)) { span_lint_and_sugg( cx, FN_TO_NUMERIC_CAST, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to), "try", format!("{} as usize", from_snippet), diff --git a/src/tools/clippy/clippy_lints/src/casts/fn_to_numeric_cast_with_truncation.rs b/src/tools/clippy/clippy_lints/src/casts/fn_to_numeric_cast_with_truncation.rs index 0085c7b27b290..413ccffc87cf7 100644 --- a/src/tools/clippy/clippy_lints/src/casts/fn_to_numeric_cast_with_truncation.rs +++ b/src/tools/clippy/clippy_lints/src/casts/fn_to_numeric_cast_with_truncation.rs @@ -16,14 +16,15 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, match cast_from.kind() { ty::FnDef(..) | ty::FnPtr(_) => { let mut applicability = Applicability::MaybeIncorrect; - let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability); + let from_snippet = + snippet_with_applicability(cx, cx.tcx.hir().span(cast_expr.hir_id), "x", &mut applicability); let to_nbits = utils::int_ty_to_nbits(cast_to, cx.tcx); if to_nbits < cx.tcx.data_layout.pointer_size.bits() { span_lint_and_sugg( cx, FN_TO_NUMERIC_CAST_WITH_TRUNCATION, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!( "casting function pointer `{}` to `{}`, which truncates the value", from_snippet, cast_to diff --git a/src/tools/clippy/clippy_lints/src/casts/mod.rs b/src/tools/clippy/clippy_lints/src/casts/mod.rs index b726bd75f1d83..fc57e091a7ea1 100644 --- a/src/tools/clippy/clippy_lints/src/casts/mod.rs +++ b/src/tools/clippy/clippy_lints/src/casts/mod.rs @@ -369,7 +369,7 @@ impl_lint_pass!(Casts => [ impl<'tcx> LateLintPass<'tcx> for Casts { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if expr.span.from_expansion() { + if cx.tcx.hir().span(expr.hir_id).from_expansion() { return; } @@ -388,7 +388,10 @@ impl<'tcx> LateLintPass<'tcx> for Casts { fn_to_numeric_cast::check(cx, expr, cast_expr, cast_from, cast_to); fn_to_numeric_cast_with_truncation::check(cx, expr, cast_expr, cast_from, cast_to); - if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) { + if cast_from.is_numeric() + && cast_to.is_numeric() + && !in_external_macro(cx.sess(), cx.tcx.hir().span(expr.hir_id)) + { cast_possible_truncation::check(cx, expr, cast_from, cast_to); cast_possible_wrap::check(cx, expr, cast_from, cast_to); cast_precision_loss::check(cx, expr, cast_from, cast_to); diff --git a/src/tools/clippy/clippy_lints/src/casts/ptr_as_ptr.rs b/src/tools/clippy/clippy_lints/src/casts/ptr_as_ptr.rs index abfbadf3642be..356da405a169e 100644 --- a/src/tools/clippy/clippy_lints/src/casts/ptr_as_ptr.rs +++ b/src/tools/clippy/clippy_lints/src/casts/ptr_as_ptr.rs @@ -29,7 +29,7 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: &Option< (Mutability::Not, Mutability::Not) | (Mutability::Mut, Mutability::Mut)); // The `U` in `pointer::cast` have to be `Sized` // as explained here: https://github.com/rust-lang/rust/issues/60602. - if to_pointee_ty.is_sized(cx.tcx.at(expr.span), cx.param_env); + if to_pointee_ty.is_sized(cx.tcx.at(cx.tcx.hir().span(expr.hir_id)), cx.param_env); then { let mut applicability = Applicability::MachineApplicable; let cast_expr_sugg = Sugg::hir_with_applicability(cx, cast_expr, "_", &mut applicability); @@ -41,7 +41,7 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: &Option< span_lint_and_sugg( cx, PTR_AS_PTR, - expr.span, + cx.tcx.hir().span(expr.hir_id), "`as` casting between raw pointers without changing its mutability", "try `pointer::cast`, a safer alternative", format!("{}.cast{}()", cast_expr_sugg.maybe_par(), turbofish), diff --git a/src/tools/clippy/clippy_lints/src/casts/unnecessary_cast.rs b/src/tools/clippy/clippy_lints/src/casts/unnecessary_cast.rs index fa2a07ef1da0c..577485bd35f76 100644 --- a/src/tools/clippy/clippy_lints/src/casts/unnecessary_cast.rs +++ b/src/tools/clippy/clippy_lints/src/casts/unnecessary_cast.rs @@ -19,7 +19,7 @@ pub(super) fn check( cast_to: Ty<'_>, ) -> bool { if let Some(lit) = get_numeric_literal(cast_expr) { - let literal_str = snippet_opt(cx, cast_expr.span).unwrap_or_default(); + let literal_str = snippet_opt(cx, cx.tcx.hir().span(cast_expr.hir_id)).unwrap_or_default(); if_chain! { if let LitKind::Int(n, _) = lit.node; @@ -45,11 +45,11 @@ pub(super) fn check( }, LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {}, _ => { - if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), expr.span) { + if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), cx.tcx.hir().span(expr.hir_id)) { span_lint( cx, UNNECESSARY_CAST, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!( "casting to the same type is unnecessary (`{}` -> `{}`)", cast_from, cast_to @@ -69,7 +69,7 @@ fn lint_unnecessary_cast(cx: &LateContext<'_>, expr: &Expr<'_>, literal_str: &st span_lint_and_sugg( cx, UNNECESSARY_CAST, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("casting {} literal to `{}` is unnecessary", literal_kind_name, cast_to), "try", format!("{}_{}", literal_str.trim_end_matches('.'), cast_to), diff --git a/src/tools/clippy/clippy_lints/src/checked_conversions.rs b/src/tools/clippy/clippy_lints/src/checked_conversions.rs index 54bc69e058bc7..3343dab2546d9 100644 --- a/src/tools/clippy/clippy_lints/src/checked_conversions.rs +++ b/src/tools/clippy/clippy_lints/src/checked_conversions.rs @@ -62,7 +62,7 @@ impl<'tcx> LateLintPass<'tcx> for CheckedConversions { } let result = if_chain! { - if !in_external_macro(cx.sess(), item.span); + if !in_external_macro(cx.sess(), cx.tcx.hir().span(item.hir_id)); if let ExprKind::Binary(op, ref left, ref right) = &item.kind; then { @@ -79,11 +79,13 @@ impl<'tcx> LateLintPass<'tcx> for CheckedConversions { if let Some(cv) = result { if let Some(to_type) = cv.to_type { let mut applicability = Applicability::MachineApplicable; - let snippet = snippet_with_applicability(cx, cv.expr_to_cast.span, "_", &mut applicability); + let snippet = snippet_with_applicability( + cx, cx.tcx.hir().span(cv.expr_to_cast.hir_id), "_", &mut applicability + ); span_lint_and_sugg( cx, CHECKED_CONVERSIONS, - item.span, + cx.tcx.hir().span(item.hir_id), "checked cast can be simplified", "try", format!("{}::try_from({}).is_ok()", to_type, snippet), diff --git a/src/tools/clippy/clippy_lints/src/collapsible_match.rs b/src/tools/clippy/clippy_lints/src/collapsible_match.rs index 3e9d3eb100fb7..77fa44c240bca 100644 --- a/src/tools/clippy/clippy_lints/src/collapsible_match.rs +++ b/src/tools/clippy/clippy_lints/src/collapsible_match.rs @@ -65,7 +65,7 @@ fn check_arm<'tcx>(arm: &Arm<'tcx>, wild_outer_arm: &Arm<'tcx>, 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() == cx.tcx.hir().span(arm.pat.hir_id).ctxt(); + if cx.tcx.hir().span(expr_in.hir_id).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,7 +95,7 @@ fn check_arm<'tcx>(arm: &Arm<'tcx>, wild_outer_arm: &Arm<'tcx>, cx: &LateContext span_lint_and_then( cx, COLLAPSIBLE_MATCH, - expr.span, + cx.tcx.hir().span(expr.hir_id), "unnecessary nested match", |diag| { let binding_span = cx.tcx.hir().span(binding_span); diff --git a/src/tools/clippy/clippy_lints/src/comparison_chain.rs b/src/tools/clippy/clippy_lints/src/comparison_chain.rs index e309db25995fb..c8d13cb875f52 100644 --- a/src/tools/clippy/clippy_lints/src/comparison_chain.rs +++ b/src/tools/clippy/clippy_lints/src/comparison_chain.rs @@ -55,7 +55,7 @@ declare_lint_pass!(ComparisonChain => [COMPARISON_CHAIN]); impl<'tcx> LateLintPass<'tcx> for ComparisonChain { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if expr.span.from_expansion() { + if cx.tcx.hir().span(expr.hir_id).from_expansion() { return; } @@ -114,7 +114,7 @@ impl<'tcx> LateLintPass<'tcx> for ComparisonChain { span_lint_and_help( cx, COMPARISON_CHAIN, - expr.span, + cx.tcx.hir().span(expr.hir_id), "`if` chain can be rewritten with `match`", None, "consider rewriting the `if` chain to use `cmp` and `match`", diff --git a/src/tools/clippy/clippy_lints/src/copies.rs b/src/tools/clippy/clippy_lints/src/copies.rs index ffa8221789804..1ea540fd9752c 100644 --- a/src/tools/clippy/clippy_lints/src/copies.rs +++ b/src/tools/clippy/clippy_lints/src/copies.rs @@ -107,7 +107,7 @@ declare_lint_pass!(CopyAndPaste => [IFS_SAME_COND, SAME_FUNCTIONS_IN_IF_CONDITIO impl<'tcx> LateLintPass<'tcx> for CopyAndPaste { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if !expr.span.from_expansion() { + if !cx.tcx.hir().span(expr.hir_id).from_expansion() { // skip ifs directly in else, it will be checked in the parent if if let Some(&Expr { kind: ExprKind::If(_, _, Some(ref else_expr)), @@ -158,9 +158,9 @@ fn lint_same_cond(cx: &LateContext<'_>, conds: &[&Expr<'_>]) { span_lint_and_note( cx, IFS_SAME_COND, - j.span, + cx.tcx.hir().span(j.hir_id), "this `if` has the same condition as a previous `if`", - Some(i.span), + Some(cx.tcx.hir().span(i.hir_id)), "same as this", ); } @@ -176,7 +176,7 @@ fn lint_same_fns_in_if_cond(cx: &LateContext<'_>, conds: &[&Expr<'_>]) { let eq: &dyn Fn(&&Expr<'_>, &&Expr<'_>) -> bool = &|&lhs, &rhs| -> bool { // Do not lint if any expr originates from a macro - if in_macro(lhs.span) || in_macro(rhs.span) { + if in_macro(cx.tcx.hir().span(lhs.hir_id)) || in_macro(cx.tcx.hir().span(rhs.hir_id)) { return false; } // Do not spawn warning if `IFS_SAME_COND` already produced it. @@ -190,9 +190,9 @@ fn lint_same_fns_in_if_cond(cx: &LateContext<'_>, conds: &[&Expr<'_>]) { span_lint_and_note( cx, SAME_FUNCTIONS_IN_IF_CONDITION, - j.span, + cx.tcx.hir().span(j.hir_id), "this `if` has the same function call as a previous `if`", - Some(i.span), + Some(cx.tcx.hir().span(i.hir_id)), "same as this", ); } diff --git a/src/tools/clippy/clippy_lints/src/create_dir.rs b/src/tools/clippy/clippy_lints/src/create_dir.rs index 200b6a565cc43..351032624ce67 100644 --- a/src/tools/clippy/clippy_lints/src/create_dir.rs +++ b/src/tools/clippy/clippy_lints/src/create_dir.rs @@ -39,10 +39,10 @@ impl LateLintPass<'_> for CreateDir { span_lint_and_sugg( cx, CREATE_DIR, - expr.span, + cx.tcx.hir().span(expr.hir_id), "calling `std::fs::create_dir` where there may be a better way", "consider calling `std::fs::create_dir_all` instead", - format!("create_dir_all({})", snippet(cx, args[0].span, "..")), + format!("create_dir_all({})", snippet(cx, cx.tcx.hir().span(args[0].hir_id), "..")), Applicability::MaybeIncorrect, ) } diff --git a/src/tools/clippy/clippy_lints/src/default.rs b/src/tools/clippy/clippy_lints/src/default.rs index 820ed380909f6..099dc6d8ef115 100644 --- a/src/tools/clippy/clippy_lints/src/default.rs +++ b/src/tools/clippy/clippy_lints/src/default.rs @@ -77,7 +77,7 @@ impl LateLintPass<'_> for Default { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if_chain! { // Avoid cases already linted by `field_reassign_with_default` - if !self.reassigned_linted.contains(&expr.span); + if !self.reassigned_linted.contains(&cx.tcx.hir().span(expr.hir_id)); if let ExprKind::Call(ref path, ..) = expr.kind; if !any_parent_is_automatically_derived(cx.tcx, expr.hir_id); if let ExprKind::Path(ref qpath) = path.kind; @@ -94,7 +94,7 @@ impl LateLintPass<'_> for Default { span_lint_and_sugg( cx, DEFAULT_TRAIT_ACCESS, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("calling `{}` is more clear than this expression", replacement), "try", replacement, @@ -122,7 +122,8 @@ impl LateLintPass<'_> for Default { if let StmtKind::Local(local) = stmt.kind; if let Some(expr) = local.init; if !any_parent_is_automatically_derived(cx.tcx, expr.hir_id); - if !in_external_macro(cx.tcx.sess, expr.span); + let expr_span = cx.tcx.hir().span(expr.hir_id); + if !in_external_macro(cx.tcx.sess, expr_span); // only take bindings to identifiers if let PatKind::Binding(_, binding_id, ident, _) = local.pat.kind; // only when assigning `... = Default::default()` @@ -138,7 +139,7 @@ impl LateLintPass<'_> for Default { .iter() .all(|field| field.vis.is_accessible_from(module_did, cx.tcx)); then { - (local, variant, ident.name, binding_type, expr.span) + (local, variant, ident.name, binding_type, cx.tcx.hir().span(expr.hir_id)) } else { continue; } @@ -192,7 +193,7 @@ impl LateLintPass<'_> for Default { .into_iter() .map(|(field, rhs)| { // extract and store the assigned value for help message - let value_snippet = snippet_with_macro_callsite(cx, rhs.span, ".."); + let value_snippet = snippet_with_macro_callsite(cx, cx.tcx.hir().span(rhs.hir_id), ".."); format!("{}: {}", field, value_snippet) }) .collect::>() diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index b5fb51af1c7f3..2e7ca5621afe6 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -41,7 +41,7 @@ declare_lint_pass!(Dereferencing => [ impl<'tcx> LateLintPass<'tcx> for Dereferencing { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if_chain! { - if !expr.span.from_expansion(); + if !cx.tcx.hir().span(expr.hir_id).from_expansion(); if let ExprKind::MethodCall(ref method_name, _, ref args, _) = &expr.kind; if args.len() == 1; @@ -64,7 +64,7 @@ impl<'tcx> LateLintPass<'tcx> for Dereferencing { } } let name = method_name.ident.as_str(); - lint_deref(cx, &*name, &args[0], args[0].span, expr.span); + lint_deref(cx, &*name, &args[0], cx.tcx.hir().span(args[0].hir_id), cx.tcx.hir().span(expr.hir_id)); } } } diff --git a/src/tools/clippy/clippy_lints/src/disallowed_method.rs b/src/tools/clippy/clippy_lints/src/disallowed_method.rs index 56dc6d18a58f2..1cc6ea774d882 100644 --- a/src/tools/clippy/clippy_lints/src/disallowed_method.rs +++ b/src/tools/clippy/clippy_lints/src/disallowed_method.rs @@ -80,7 +80,7 @@ impl<'tcx> LateLintPass<'tcx> for DisallowedMethod { span_lint( cx, DISALLOWED_METHOD, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("use of a disallowed method `{}`", func_path_string), ); } diff --git a/src/tools/clippy/clippy_lints/src/doc.rs b/src/tools/clippy/clippy_lints/src/doc.rs index 6c13c737808ea..33eb3e153798e 100644 --- a/src/tools/clippy/clippy_lints/src/doc.rs +++ b/src/tools/clippy/clippy_lints/src/doc.rs @@ -718,19 +718,20 @@ impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> { if let ExprKind::Path(QPath::Resolved(_, ref path)) = func_expr.kind; if let Some(path_def_id) = path.res.opt_def_id(); if match_panic_def_id(self.cx, path_def_id); - if is_expn_of(expr.span, "unreachable").is_none(); + let expr_span = self.cx.tcx.hir().span(expr.hir_id); + if is_expn_of(expr_span, "unreachable").is_none(); then { - self.panic_span = Some(expr.span); + self.panic_span = Some(expr_span); } } // check for `unwrap` - if let Some(arglists) = method_chain_args(expr, &["unwrap"]) { + if let Some(arglists) = method_chain_args(self.cx, expr, &["unwrap"]) { let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs(); if is_type_diagnostic_item(self.cx, reciever_ty, sym::option_type) || is_type_diagnostic_item(self.cx, reciever_ty, sym::result_type) { - self.panic_span = Some(expr.span); + self.panic_span = Some(self.cx.tcx.hir().span(expr.hir_id)); } } diff --git a/src/tools/clippy/clippy_lints/src/double_comparison.rs b/src/tools/clippy/clippy_lints/src/double_comparison.rs index 19f56195ec1b4..42b67e59600d3 100644 --- a/src/tools/clippy/clippy_lints/src/double_comparison.rs +++ b/src/tools/clippy/clippy_lints/src/double_comparison.rs @@ -52,8 +52,8 @@ impl<'tcx> DoubleComparisons { macro_rules! lint_double_comparison { ($op:tt) => {{ let mut applicability = Applicability::MachineApplicable; - let lhs_str = snippet_with_applicability(cx, llhs.span, "", &mut applicability); - let rhs_str = snippet_with_applicability(cx, lrhs.span, "", &mut applicability); + let lhs_str = snippet_with_applicability(cx, cx.tcx.hir().span(llhs.hir_id), "", &mut applicability); + let rhs_str = snippet_with_applicability(cx, cx.tcx.hir().span(lrhs.hir_id), "", &mut applicability); let sugg = format!("{} {} {}", lhs_str, stringify!($op), rhs_str); span_lint_and_sugg( cx, @@ -88,7 +88,7 @@ impl<'tcx> DoubleComparisons { impl<'tcx> LateLintPass<'tcx> for DoubleComparisons { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if let ExprKind::Binary(ref kind, ref lhs, ref rhs) = expr.kind { - Self::check_binop(cx, kind.node, lhs, rhs, expr.span); + Self::check_binop(cx, kind.node, lhs, rhs, cx.tcx.hir().span(expr.hir_id)); } } } diff --git a/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs b/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs index 2aea00d883c41..31238e96a469a 100644 --- a/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs +++ b/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs @@ -133,9 +133,9 @@ impl<'tcx> LateLintPass<'tcx> for DropForgetRef { } span_lint_and_note(cx, lint, - expr.span, + cx.tcx.hir().span(expr.hir_id), &msg, - Some(arg.span), + Some(cx.tcx.hir().span(arg.hir_id)), &format!("argument has type `{}`", arg_ty)); } else if is_copy(cx, arg_ty) { if match_def_path(cx, def_id, &paths::DROP) { @@ -149,9 +149,9 @@ impl<'tcx> LateLintPass<'tcx> for DropForgetRef { } span_lint_and_note(cx, lint, - expr.span, + cx.tcx.hir().span(expr.hir_id), &msg, - Some(arg.span), + Some(cx.tcx.hir().span(arg.hir_id)), &format!("argument has type {}", arg_ty)); } } diff --git a/src/tools/clippy/clippy_lints/src/duration_subsec.rs b/src/tools/clippy/clippy_lints/src/duration_subsec.rs index c0529a34cc411..9aa016bf848a8 100644 --- a/src/tools/clippy/clippy_lints/src/duration_subsec.rs +++ b/src/tools/clippy/clippy_lints/src/duration_subsec.rs @@ -55,12 +55,12 @@ impl<'tcx> LateLintPass<'tcx> for DurationSubsec { span_lint_and_sugg( cx, DURATION_SUBSEC, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("calling `{}()` is more concise than this calculation", suggested_fn), "try", format!( "{}.{}()", - snippet_with_applicability(cx, args[0].span, "_", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(args[0].hir_id), "_", &mut applicability), suggested_fn ), applicability, diff --git a/src/tools/clippy/clippy_lints/src/entry.rs b/src/tools/clippy/clippy_lints/src/entry.rs index 55575969927ba..bc588f7c5eb2b 100644 --- a/src/tools/clippy/clippy_lints/src/entry.rs +++ b/src/tools/clippy/clippy_lints/src/entry.rs @@ -72,7 +72,7 @@ impl<'tcx> LateLintPass<'tcx> for HashMapPass { let mut visitor = InsertVisitor { cx, - span: expr.span, + span: cx.tcx.hir().span(expr.hir_id), ty, map, key, @@ -85,7 +85,7 @@ impl<'tcx> LateLintPass<'tcx> for HashMapPass { if let Some((ty, map, key)) = check_cond(cx, check) { let mut visitor = InsertVisitor { cx, - span: expr.span, + span: cx.tcx.hir().span(expr.hir_id), ty, map, key, @@ -143,16 +143,16 @@ impl<'a, 'tcx, 'b> Visitor<'tcx> for InsertVisitor<'a, 'tcx, 'b> { if path.ident.name == sym!(insert); if get_item_name(self.cx, self.map) == get_item_name(self.cx, ¶ms[0]); if SpanlessEq::new(self.cx).eq_expr(self.key, ¶ms[1]); - if snippet_opt(self.cx, self.map.span) == snippet_opt(self.cx, params[0].span); + if snippet_opt(self.cx, self.cx.tcx.hir().span(self.map.hir_id)) == snippet_opt(self.cx, self.cx.tcx.hir().span(params[0].hir_id)); then { span_lint_and_then(self.cx, MAP_ENTRY, self.span, &format!("usage of `contains_key` followed by `insert` on a `{}`", self.ty), |diag| { if self.sole_expr { let mut app = Applicability::MachineApplicable; let help = format!("{}.entry({}).or_insert({});", - snippet_with_applicability(self.cx, self.map.span, "map", &mut app), - snippet_with_applicability(self.cx, params[1].span, "..", &mut app), - snippet_with_applicability(self.cx, params[2].span, "..", &mut app)); + snippet_with_applicability(self.cx, self.cx.tcx.hir().span(self.map.hir_id), "map", &mut app), + snippet_with_applicability(self.cx, self.cx.tcx.hir().span(params[1].hir_id), "..", &mut app), + snippet_with_applicability(self.cx, self.cx.tcx.hir().span(params[2].hir_id), "..", &mut app)); diag.span_suggestion( self.span, @@ -163,8 +163,8 @@ impl<'a, 'tcx, 'b> Visitor<'tcx> for InsertVisitor<'a, 'tcx, 'b> { } else { let help = format!("consider using `{}.entry({})`", - snippet(self.cx, self.map.span, "map"), - snippet(self.cx, params[1].span, "..")); + snippet(self.cx, self.cx.tcx.hir().span(self.map.hir_id), "map"), + snippet(self.cx, self.cx.tcx.hir().span(params[1].hir_id), "..")); diag.span_label( self.span, diff --git a/src/tools/clippy/clippy_lints/src/eq_op.rs b/src/tools/clippy/clippy_lints/src/eq_op.rs index 089b512d9b85e..0c29099513b1b 100644 --- a/src/tools/clippy/clippy_lints/src/eq_op.rs +++ b/src/tools/clippy/clippy_lints/src/eq_op.rs @@ -81,7 +81,7 @@ impl<'tcx> LateLintPass<'tcx> for EqOp { span_lint( cx, EQ_OP, - lhs.span.to(rhs.span), + cx.tcx.hir().span(lhs.hir_id).to(cx.tcx.hir().span(rhs.hir_id)), &format!("identical args used in this `{}!` macro call", amn), ); } @@ -90,12 +90,12 @@ impl<'tcx> LateLintPass<'tcx> for EqOp { } } if let ExprKind::Binary(op, ref left, ref right) = e.kind { - if e.span.from_expansion() { + if cx.tcx.hir().span(e.hir_id).from_expansion() { return; } let macro_with_not_op = |expr_kind: &ExprKind<'_>| { if let ExprKind::Unary(_, ref expr) = *expr_kind { - in_macro(expr.span) + in_macro(cx.tcx.hir().span(expr.hir_id)) } else { false } @@ -107,7 +107,7 @@ impl<'tcx> LateLintPass<'tcx> for EqOp { span_lint( cx, EQ_OP, - e.span, + cx.tcx.hir().span(e.hir_id), &format!("equal expressions as operands to `{}`", op.node.as_str()), ); return; @@ -146,15 +146,15 @@ impl<'tcx> LateLintPass<'tcx> for EqOp { span_lint_and_then( cx, OP_REF, - e.span, + cx.tcx.hir().span(e.hir_id), "needlessly taken reference of both operands", |diag| { - let lsnip = snippet(cx, l.span, "...").to_string(); - let rsnip = snippet(cx, r.span, "...").to_string(); + let lsnip = snippet(cx, cx.tcx.hir().span(l.hir_id), "...").to_string(); + let rsnip = snippet(cx, cx.tcx.hir().span(r.hir_id), "...").to_string(); multispan_sugg( diag, "use the values directly", - vec![(left.span, lsnip), (right.span, rsnip)], + vec![(cx.tcx.hir().span(left.hir_id), lsnip), (cx.tcx.hir().span(right.hir_id), rsnip)], ); }, ) @@ -165,12 +165,12 @@ impl<'tcx> LateLintPass<'tcx> for EqOp { span_lint_and_then( cx, OP_REF, - e.span, + cx.tcx.hir().span(e.hir_id), "needlessly taken reference of left operand", |diag| { - let lsnip = snippet(cx, l.span, "...").to_string(); + let lsnip = snippet(cx, cx.tcx.hir().span(l.hir_id), "...").to_string(); diag.span_suggestion( - left.span, + cx.tcx.hir().span(left.hir_id), "use the left value directly", lsnip, Applicability::MaybeIncorrect, // FIXME #2597 @@ -184,12 +184,12 @@ impl<'tcx> LateLintPass<'tcx> for EqOp { span_lint_and_then( cx, OP_REF, - e.span, + cx.tcx.hir().span(e.hir_id), "needlessly taken reference of right operand", |diag| { - let rsnip = snippet(cx, r.span, "...").to_string(); + let rsnip = snippet(cx, cx.tcx.hir().span(r.hir_id), "...").to_string(); diag.span_suggestion( - right.span, + cx.tcx.hir().span(right.hir_id), "use the right value directly", rsnip, Applicability::MaybeIncorrect, // FIXME #2597 @@ -208,12 +208,12 @@ impl<'tcx> LateLintPass<'tcx> for EqOp { span_lint_and_then( cx, OP_REF, - e.span, + cx.tcx.hir().span(e.hir_id), "needlessly taken reference of left operand", |diag| { - let lsnip = snippet(cx, l.span, "...").to_string(); + let lsnip = snippet(cx, cx.tcx.hir().span(l.hir_id), "...").to_string(); diag.span_suggestion( - left.span, + cx.tcx.hir().span(left.hir_id), "use the left value directly", lsnip, Applicability::MaybeIncorrect, // FIXME #2597 @@ -229,10 +229,10 @@ impl<'tcx> LateLintPass<'tcx> for EqOp { if (requires_ref || rcpy) && implements_trait(cx, cx.typeck_results().expr_ty(left), trait_id, &[rty.into()]) { - span_lint_and_then(cx, OP_REF, e.span, "taken reference of right operand", |diag| { - let rsnip = snippet(cx, r.span, "...").to_string(); + span_lint_and_then(cx, OP_REF, cx.tcx.hir().span(e.hir_id), "taken reference of right operand", |diag| { + let rsnip = snippet(cx, cx.tcx.hir().span(r.hir_id), "...").to_string(); diag.span_suggestion( - right.span, + cx.tcx.hir().span(right.hir_id), "use the right value directly", rsnip, Applicability::MaybeIncorrect, // FIXME #2597 diff --git a/src/tools/clippy/clippy_lints/src/erasing_op.rs b/src/tools/clippy/clippy_lints/src/erasing_op.rs index dbd1ff514f0e1..917378442c949 100644 --- a/src/tools/clippy/clippy_lints/src/erasing_op.rs +++ b/src/tools/clippy/clippy_lints/src/erasing_op.rs @@ -31,16 +31,16 @@ declare_lint_pass!(ErasingOp => [ERASING_OP]); impl<'tcx> LateLintPass<'tcx> for ErasingOp { fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { - if e.span.from_expansion() { + if cx.tcx.hir().span(e.hir_id).from_expansion() { return; } if let ExprKind::Binary(ref cmp, ref left, ref right) = e.kind { match cmp.node { BinOpKind::Mul | BinOpKind::BitAnd => { - check(cx, left, e.span); - check(cx, right, e.span); + check(cx, left, cx.tcx.hir().span(e.hir_id)); + check(cx, right, cx.tcx.hir().span(e.hir_id)); }, - BinOpKind::Div => check(cx, left, e.span), + BinOpKind::Div => check(cx, left, cx.tcx.hir().span(e.hir_id)), _ => (), } } diff --git a/src/tools/clippy/clippy_lints/src/eta_reduction.rs b/src/tools/clippy/clippy_lints/src/eta_reduction.rs index c461732fd3693..342cca2a0445e 100644 --- a/src/tools/clippy/clippy_lints/src/eta_reduction.rs +++ b/src/tools/clippy/clippy_lints/src/eta_reduction.rs @@ -69,7 +69,7 @@ declare_lint_pass!(EtaReduction => [REDUNDANT_CLOSURE, REDUNDANT_CLOSURE_FOR_MET impl<'tcx> LateLintPass<'tcx> for EtaReduction { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), cx.tcx.hir().span(expr.hir_id)) { return; } @@ -77,7 +77,7 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction { ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args, _) => { for arg in args { // skip `foo(macro!())` - if arg.span.ctxt() == expr.span.ctxt() { + if cx.tcx.hir().span(arg.hir_id).ctxt() == cx.tcx.hir().span(expr.hir_id).ctxt() { check_closure(cx, arg) } } @@ -92,13 +92,13 @@ fn check_closure(cx: &LateContext<'_>, expr: &Expr<'_>) { let body = cx.tcx.hir().body(eid); let ex = &body.value; - if ex.span.ctxt() != expr.span.ctxt() { + if cx.tcx.hir().span(ex.hir_id).ctxt() != cx.tcx.hir().span(expr.hir_id).ctxt() { if let Some(VecArgs::Vec(&[])) = higher::vec_macro(cx, ex) { // replace `|| vec![]` with `Vec::new` span_lint_and_sugg( cx, REDUNDANT_CLOSURE, - expr.span, + cx.tcx.hir().span(expr.hir_id), "redundant closure", "replace the closure with `Vec::new`", "std::vec::Vec::new".into(), @@ -129,10 +129,10 @@ fn check_closure(cx: &LateContext<'_>, expr: &Expr<'_>) { if compare_inputs(&mut iter_input_pats(decl, body), &mut args.iter()); then { - span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure", |diag| { - if let Some(snippet) = snippet_opt(cx, caller.span) { + span_lint_and_then(cx, REDUNDANT_CLOSURE, cx.tcx.hir().span(expr.hir_id), "redundant closure", |diag| { + if let Some(snippet) = snippet_opt(cx, cx.tcx.hir().span(caller.hir_id)) { diag.span_suggestion( - expr.span, + cx.tcx.hir().span(expr.hir_id), "replace the closure with the function itself", snippet, Applicability::MachineApplicable, @@ -162,7 +162,7 @@ fn check_closure(cx: &LateContext<'_>, expr: &Expr<'_>) { span_lint_and_sugg( cx, REDUNDANT_CLOSURE_FOR_METHOD_CALLS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "redundant closure", "replace the closure with the method itself", format!("{}::{}", name, path.ident.name), diff --git a/src/tools/clippy/clippy_lints/src/eval_order_dependence.rs b/src/tools/clippy/clippy_lints/src/eval_order_dependence.rs index 83cee11c3a859..ff4f22bc80634 100644 --- a/src/tools/clippy/clippy_lints/src/eval_order_dependence.rs +++ b/src/tools/clippy/clippy_lints/src/eval_order_dependence.rs @@ -119,7 +119,12 @@ impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> { } } fn report_diverging_sub_expr(&mut self, e: &Expr<'_>) { - span_lint(self.cx, DIVERGING_SUB_EXPRESSION, e.span, "sub-expression diverges"); + span_lint( + self.cx, + DIVERGING_SUB_EXPRESSION, + self.cx.tcx.hir().span(e.hir_id), + "sub-expression diverges", + ); } } @@ -303,9 +308,9 @@ impl<'a, 'tcx> Visitor<'tcx> for ReadVisitor<'a, 'tcx> { span_lint_and_note( self.cx, EVAL_ORDER_DEPENDENCE, - expr.span, + self.cx.tcx.hir().span(expr.hir_id), "unsequenced read of a variable", - Some(self.write_expr.span), + Some(self.cx.tcx.hir().span(self.write_expr.hir_id)), "whether read occurs before this write depends on evaluation order", ); } diff --git a/src/tools/clippy/clippy_lints/src/exit.rs b/src/tools/clippy/clippy_lints/src/exit.rs index 915859270009b..7cbadda3f9dd3 100644 --- a/src/tools/clippy/clippy_lints/src/exit.rs +++ b/src/tools/clippy/clippy_lints/src/exit.rs @@ -38,7 +38,7 @@ impl<'tcx> LateLintPass<'tcx> for Exit { // and only then emit a linter warning let def_id = cx.tcx.hir().local_def_id(parent); if !is_entrypoint_fn(cx, def_id.to_def_id()) { - span_lint(cx, EXIT, e.span, "usage of `process::exit`"); + span_lint(cx, EXIT, cx.tcx.hir().span(e.hir_id), "usage of `process::exit`"); } } } diff --git a/src/tools/clippy/clippy_lints/src/explicit_write.rs b/src/tools/clippy/clippy_lints/src/explicit_write.rs index f8038d06e5034..747b6ce6c6377 100644 --- a/src/tools/clippy/clippy_lints/src/explicit_write.rs +++ b/src/tools/clippy/clippy_lints/src/explicit_write.rs @@ -50,7 +50,8 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitWrite { None }; then { - let write_span = unwrap_args[0].span; + let expr_span = cx.tcx.hir().span(expr.hir_id); + let write_span = cx.tcx.hir().span(unwrap_args[0].hir_id); let calling_macro = // ordering is important here, since `writeln!` uses `write!` internally if is_expn_of(write_span, "writeln").is_some() { @@ -78,7 +79,7 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitWrite { span_lint_and_sugg( cx, EXPLICIT_WRITE, - expr.span, + expr_span, &format!( "use of `{}!({}(), ...).unwrap()`", macro_name, @@ -92,7 +93,7 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitWrite { span_lint_and_sugg( cx, EXPLICIT_WRITE, - expr.span, + expr_span, &format!("use of `{}().write_fmt(...).unwrap()`", dest_name), "try this", format!("{}print!(\"{}\")", prefix, write_output.escape_default()), @@ -105,7 +106,7 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitWrite { span_lint( cx, EXPLICIT_WRITE, - expr.span, + expr_span, &format!( "use of `{}!({}(), ...).unwrap()`. Consider using `{}{}!` instead", macro_name, @@ -118,7 +119,7 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitWrite { span_lint( cx, EXPLICIT_WRITE, - expr.span, + expr_span, &format!("use of `{}().write_fmt(...).unwrap()`. Consider using `{}print!` instead", dest_name, prefix), ); } diff --git a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs index bf854c94b6700..c37933fd763b3 100644 --- a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs +++ b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs @@ -77,25 +77,27 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[h type Map = Map<'tcx>; fn visit_expr(&mut self, expr: &'tcx Expr<'_>) { + let expr_span = self.lcx.tcx.hir().span(expr.hir_id); + // check for `begin_panic` if_chain! { if let ExprKind::Call(ref func_expr, _) = expr.kind; if let ExprKind::Path(QPath::Resolved(_, ref path)) = func_expr.kind; if let Some(path_def_id) = path.res.opt_def_id(); if match_panic_def_id(self.lcx, path_def_id); - if is_expn_of(expr.span, "unreachable").is_none(); + if is_expn_of(expr_span, "unreachable").is_none(); then { - self.result.push(expr.span); + self.result.push(expr_span); } } // check for `unwrap` - if let Some(arglists) = method_chain_args(expr, &["unwrap"]) { + if let Some(arglists) = method_chain_args(self.lcx, expr, &["unwrap"]) { let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs(); if is_type_diagnostic_item(self.lcx, reciever_ty, sym::option_type) || is_type_diagnostic_item(self.lcx, reciever_ty, sym::result_type) { - self.result.push(expr.span); + self.result.push(expr_span); } } diff --git a/src/tools/clippy/clippy_lints/src/float_equality_without_abs.rs b/src/tools/clippy/clippy_lints/src/float_equality_without_abs.rs index c1c08597ee670..89d1ffc29f4f1 100644 --- a/src/tools/clippy/clippy_lints/src/float_equality_without_abs.rs +++ b/src/tools/clippy/clippy_lints/src/float_equality_without_abs.rs @@ -95,11 +95,11 @@ impl<'tcx> LateLintPass<'tcx> for FloatEqualityWithoutAbs { span_lint_and_then( cx, FLOAT_EQUALITY_WITHOUT_ABS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "float equality check without `.abs()`", | diag | { diag.span_suggestion( - lhs.span, + cx.tcx.hir().span(lhs.hir_id), "add `.abs()`", suggestion, Applicability::MaybeIncorrect, diff --git a/src/tools/clippy/clippy_lints/src/float_literal.rs b/src/tools/clippy/clippy_lints/src/float_literal.rs index 8e256f3468419..aff427fc5826e 100644 --- a/src/tools/clippy/clippy_lints/src/float_literal.rs +++ b/src/tools/clippy/clippy_lints/src/float_literal.rs @@ -105,7 +105,7 @@ impl<'tcx> LateLintPass<'tcx> for FloatLiteral { span_lint_and_sugg( cx, LOSSY_FLOAT_LITERAL, - expr.span, + cx.tcx.hir().span(expr.hir_id), "literal cannot be represented as the underlying type without loss of precision", "consider changing the type or replacing it with", numeric_literal::format(&float_str, type_suffix, true), @@ -116,7 +116,7 @@ impl<'tcx> LateLintPass<'tcx> for FloatLiteral { span_lint_and_sugg( cx, EXCESSIVE_PRECISION, - expr.span, + cx.tcx.hir().span(expr.hir_id), "float has excessive precision", "consider changing the type or truncating it to", numeric_literal::format(&float_str, type_suffix, true), diff --git a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs index 086a791520fa8..772bf26649549 100644 --- a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs +++ b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs @@ -168,7 +168,7 @@ fn check_log_base(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) { span_lint_and_sugg( cx, SUBOPTIMAL_FLOPS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "logarithm for bases 2, 10 and e can be computed more accurately", "consider using", format!("{}.{}()", Sugg::hir(cx, &args[0], ".."), method), @@ -200,7 +200,7 @@ fn check_ln1p(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) { span_lint_and_sugg( cx, IMPRECISE_FLOPS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "ln(1 + x) can be computed more accurately", "consider using", format!("{}.ln_1p()", prepare_receiver_sugg(cx, recv)), @@ -248,7 +248,7 @@ fn check_powf(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) { span_lint_and_sugg( cx, SUBOPTIMAL_FLOPS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "exponent for bases 2 and e can be computed more accurately", "consider using", format!("{}.{}()", prepare_receiver_sugg(cx, &args[1]), method), @@ -287,7 +287,7 @@ fn check_powf(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) { span_lint_and_sugg( cx, lint, - expr.span, + cx.tcx.hir().span(expr.hir_id), help, "consider using", suggestion, @@ -321,7 +321,7 @@ fn check_powi(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) { span_lint_and_sugg( cx, SUBOPTIMAL_FLOPS, - parent.span, + cx.tcx.hir().span(parent.hir_id), "square can be computed more efficiently", "consider using", format!( @@ -340,7 +340,7 @@ fn check_powi(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) { span_lint_and_sugg( cx, SUBOPTIMAL_FLOPS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "square can be computed more efficiently", "consider using", format!("{} * {}", Sugg::hir(cx, &args[0], ".."), Sugg::hir(cx, &args[0], "..")), @@ -402,7 +402,7 @@ fn check_hypot(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) { span_lint_and_sugg( cx, IMPRECISE_FLOPS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "hypotenuse can be computed more accurately", "consider using", message, @@ -426,7 +426,7 @@ fn check_expm1(cx: &LateContext<'_>, expr: &Expr<'_>) { span_lint_and_sugg( cx, IMPRECISE_FLOPS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "(e.pow(x) - 1) can be computed more accurately", "consider using", format!( @@ -481,7 +481,7 @@ fn check_mul_add(cx: &LateContext<'_>, expr: &Expr<'_>) { span_lint_and_sugg( cx, SUBOPTIMAL_FLOPS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "multiply and add expressions can be calculated more efficiently and accurately", "consider using", format!( @@ -591,7 +591,7 @@ fn check_custom_abs(cx: &LateContext<'_>, expr: &Expr<'_>) { span_lint_and_sugg( cx, SUBOPTIMAL_FLOPS, - expr.span, + cx.tcx.hir().span(expr.hir_id), sugg.0, "try", sugg.1, @@ -635,7 +635,7 @@ fn check_log_division(cx: &LateContext<'_>, expr: &Expr<'_>) { span_lint_and_sugg( cx, SUBOPTIMAL_FLOPS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "log base can be expressed more clearly", "consider using", format!("{}.log({})", Sugg::hir(cx, &largs[0], ".."), Sugg::hir(cx, &rargs[0], ".."),), @@ -671,7 +671,7 @@ fn check_radians(cx: &LateContext<'_>, expr: &Expr<'_>) { span_lint_and_sugg( cx, SUBOPTIMAL_FLOPS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "conversion to degrees can be done more accurately", "consider using", format!("{}.to_degrees()", Sugg::hir(cx, &mul_lhs, "..")), @@ -684,7 +684,7 @@ fn check_radians(cx: &LateContext<'_>, expr: &Expr<'_>) { span_lint_and_sugg( cx, SUBOPTIMAL_FLOPS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "conversion to radians can be done more accurately", "consider using", format!("{}.to_radians()", Sugg::hir(cx, &mul_lhs, "..")), diff --git a/src/tools/clippy/clippy_lints/src/format.rs b/src/tools/clippy/clippy_lints/src/format.rs index fd6bf19db94c8..03daba15e58f8 100644 --- a/src/tools/clippy/clippy_lints/src/format.rs +++ b/src/tools/clippy/clippy_lints/src/format.rs @@ -43,7 +43,7 @@ declare_lint_pass!(UselessFormat => [USELESS_FORMAT]); impl<'tcx> LateLintPass<'tcx> for UselessFormat { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - let span = match is_expn_of(expr.span, "format") { + let span = match is_expn_of(cx.tcx.hir().span(expr.hir_id), "format") { Some(s) if !s.from_expansion() => s, _ => return, }; @@ -100,7 +100,7 @@ fn on_argumentv1_new<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, arms: & return Some(format!("{:?}.to_string()", s.as_str())); } } else { - let snip = snippet(cx, format_args.span, ""); + let snip = snippet(cx, cx.tcx.hir().span(format_args.hir_id), ""); if let ExprKind::MethodCall(ref path, _, _, _) = format_args.kind { if path.ident.name == sym!(to_string) { return Some(format!("{}", snip)); diff --git a/src/tools/clippy/clippy_lints/src/from_str_radix_10.rs b/src/tools/clippy/clippy_lints/src/from_str_radix_10.rs index 0933f9830147c..ca307a406e405 100644 --- a/src/tools/clippy/clippy_lints/src/from_str_radix_10.rs +++ b/src/tools/clippy/clippy_lints/src/from_str_radix_10.rs @@ -84,7 +84,7 @@ impl LateLintPass<'tcx> for FromStrRadix10 { span_lint_and_sugg( cx, FROM_STR_RADIX_10, - exp.span, + cx.tcx.hir().span(exp.hir_id), "this call to `from_str_radix` can be replaced with a call to `str::parse`", "try", format!("{}.parse::<{}>()", sugg, prim_ty.name_str()), diff --git a/src/tools/clippy/clippy_lints/src/functions.rs b/src/tools/clippy/clippy_lints/src/functions.rs index 98cd421b5bfa8..7071614ecef75 100644 --- a/src/tools/clippy/clippy_lints/src/functions.rs +++ b/src/tools/clippy/clippy_lints/src/functions.rs @@ -405,7 +405,7 @@ impl<'tcx> Functions { return; } - let code_snippet = snippet(cx, body.value.span, ".."); + let code_snippet = snippet(cx, cx.tcx.hir().span(body.value.hir_id), ".."); let mut line_count: u64 = 0; let mut in_comment = false; let mut code_in_line; @@ -681,7 +681,7 @@ impl<'a, 'tcx> DerefVisitor<'a, 'tcx> { span_lint( self.cx, NOT_UNSAFE_PTR_ARG_DEREF, - ptr.span, + self.cx.tcx.hir().span(ptr.hir_id), "this public function dereferences a raw pointer but is not marked `unsafe`", ); } @@ -711,7 +711,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> { && is_mutable_ty( self.cx, self.cx.tcx.typeck(arg.hir_id.owner).expr_ty(arg), - arg.span, + self.cx.tcx.hir().span(arg.hir_id), &mut tys, ) && is_mutated_static(arg) diff --git a/src/tools/clippy/clippy_lints/src/get_last_with_len.rs b/src/tools/clippy/clippy_lints/src/get_last_with_len.rs index cdd8a42e7cd12..1c4db81568e44 100644 --- a/src/tools/clippy/clippy_lints/src/get_last_with_len.rs +++ b/src/tools/clippy/clippy_lints/src/get_last_with_len.rs @@ -85,14 +85,14 @@ impl<'tcx> LateLintPass<'tcx> for GetLastWithLen { let mut applicability = Applicability::MachineApplicable; let vec_name = snippet_with_applicability( cx, - struct_calling_on.span, "vec", + cx.tcx.hir().span(struct_calling_on.hir_id), "vec", &mut applicability, ); span_lint_and_sugg( cx, GET_LAST_WITH_LEN, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("accessing last element with `{0}.get({0}.len() - 1)`", vec_name), "try", format!("{}.last()", vec_name), diff --git a/src/tools/clippy/clippy_lints/src/identity_op.rs b/src/tools/clippy/clippy_lints/src/identity_op.rs index 8501d34770201..198c947af00b0 100644 --- a/src/tools/clippy/clippy_lints/src/identity_op.rs +++ b/src/tools/clippy/clippy_lints/src/identity_op.rs @@ -30,7 +30,8 @@ declare_lint_pass!(IdentityOp => [IDENTITY_OP]); impl<'tcx> LateLintPass<'tcx> for IdentityOp { fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { - if e.span.from_expansion() { + let e_span = cx.tcx.hir().span(e.hir_id); + if e_span.from_expansion() { return; } if let ExprKind::Binary(cmp, ref left, ref right) = e.kind { @@ -39,18 +40,18 @@ impl<'tcx> LateLintPass<'tcx> for IdentityOp { } match cmp.node { BinOpKind::Add | BinOpKind::BitOr | BinOpKind::BitXor => { - check(cx, left, 0, e.span, right.span); - check(cx, right, 0, e.span, left.span); + check(cx, left, 0, e_span, cx.tcx.hir().span(right.hir_id)); + check(cx, right, 0, e_span, cx.tcx.hir().span(left.hir_id)); }, - BinOpKind::Shl | BinOpKind::Shr | BinOpKind::Sub => check(cx, right, 0, e.span, left.span), + BinOpKind::Shl | BinOpKind::Shr | BinOpKind::Sub => check(cx, right, 0, e_span, cx.tcx.hir().span(left.hir_id)), BinOpKind::Mul => { - check(cx, left, 1, e.span, right.span); - check(cx, right, 1, e.span, left.span); + check(cx, left, 1, e_span, cx.tcx.hir().span(right.hir_id)); + check(cx, right, 1, e_span, cx.tcx.hir().span(left.hir_id)); }, - BinOpKind::Div => check(cx, right, 1, e.span, left.span), + BinOpKind::Div => check(cx, right, 1, e_span, cx.tcx.hir().span(left.hir_id)), BinOpKind::BitAnd => { - check(cx, left, -1, e.span, right.span); - check(cx, right, -1, e.span, left.span); + check(cx, left, -1, e_span, cx.tcx.hir().span(right.hir_id)); + check(cx, right, -1, e_span, cx.tcx.hir().span(left.hir_id)); }, _ => (), } diff --git a/src/tools/clippy/clippy_lints/src/if_let_mutex.rs b/src/tools/clippy/clippy_lints/src/if_let_mutex.rs index 58511c6d57c68..f516ae8432e4c 100644 --- a/src/tools/clippy/clippy_lints/src/if_let_mutex.rs +++ b/src/tools/clippy/clippy_lints/src/if_let_mutex.rs @@ -70,7 +70,7 @@ impl<'tcx> LateLintPass<'tcx> for IfLetMutex { span_lint_and_help( cx, IF_LET_MUTEX, - ex.span, + cx.tcx.hir().span(ex.hir_id), "calling `Mutex::lock` inside the scope of another `Mutex::lock` causes a deadlock", None, "move the lock call outside of the `if let ...` expression", 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 bad295c57c428..2ce3795d7dc21 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 @@ -44,14 +44,15 @@ impl<'tcx> LateLintPass<'tcx> for OkIfLet { if let ExprKind::Match(ref op, ref body, MatchSource::IfLetDesugar { .. }) = expr.kind; //test if expr is if let if let ExprKind::MethodCall(_, ok_span, ref result_types, _) = op.kind; //check is expr.ok() has type Result.ok(, _) if let PatKind::TupleStruct(QPath::Resolved(_, ref x), ref y, _) = body[0].pat.kind; //get operation - if method_chain_args(op, &["ok"]).is_some(); //test to see if using ok() methoduse std::marker::Sized; + if method_chain_args(cx, op, &["ok"]).is_some(); //test to see if using ok() methoduse std::marker::Sized; if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&result_types[0]), sym::result_type); if rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_path(x, false)) == "Some"; then { let mut applicability = Applicability::MachineApplicable; 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 op_span = cx.tcx.hir().span(op.hir_id); + let trimmed_ok = snippet_with_applicability(cx, op_span.until(ok_span), "", &mut applicability); let sugg = format!( "if let Ok({}) = {}", some_expr_string, @@ -60,7 +61,7 @@ impl<'tcx> LateLintPass<'tcx> for OkIfLet { span_lint_and_sugg( cx, IF_LET_SOME_RESULT, - expr.span.with_hi(op.span.hi()), + cx.tcx.hir().span(expr.hir_id).with_hi(op_span.hi()), "matching on `Some` with `ok()` is redundant", &format!("consider matching on `Ok({})` and removing the call to `ok` instead", some_expr_string), sugg, diff --git a/src/tools/clippy/clippy_lints/src/implicit_return.rs b/src/tools/clippy/clippy_lints/src/implicit_return.rs index 32b4fec462a5d..3a1db51a3ccc8 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_return.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_return.rs @@ -57,6 +57,7 @@ fn lint(cx: &LateContext<'_>, outer_span: Span, inner_span: Span, msg: &str) { } fn expr_match(cx: &LateContext<'_>, expr: &Expr<'_>) { + let expr_span = cx.tcx.hir().span(expr.hir_id); match expr.kind { // loops could be using `break` instead of `return` ExprKind::Block(block, ..) | ExprKind::Loop(block, ..) => { @@ -70,7 +71,8 @@ fn expr_match(cx: &LateContext<'_>, expr: &Expr<'_>) { // make sure it's a break, otherwise we want to skip if let ExprKind::Break(.., Some(break_expr)) = &expr.kind; then { - lint(cx, expr.span, break_expr.span, LINT_BREAK); + let expr_span = cx.tcx.hir().span(expr.hir_id); + lint(cx, expr_span, cx.tcx.hir().span(break_expr.hir_id), LINT_BREAK); } } } @@ -78,7 +80,7 @@ fn expr_match(cx: &LateContext<'_>, expr: &Expr<'_>) { // use `return` instead of `break` ExprKind::Break(.., break_expr) => { if let Some(break_expr) = break_expr { - lint(cx, expr.span, break_expr.span, LINT_BREAK); + lint(cx, expr_span, cx.tcx.hir().span(break_expr.hir_id), LINT_BREAK); } }, ExprKind::If(.., if_expr, else_expr) => { @@ -114,12 +116,12 @@ fn expr_match(cx: &LateContext<'_>, expr: &Expr<'_>) { if match_panic_def_id(cx, path_def_id); then { } else { - lint(cx, expr.span, expr.span, LINT_RETURN) + lint(cx, expr_span, expr_span, LINT_RETURN) } } }, // everything else is missing `return` - _ => lint(cx, expr.span, expr.span, LINT_RETURN), + _ => lint(cx, expr_span, expr_span, LINT_RETURN), } } diff --git a/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs b/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs index 16e162badb5ee..dc2b837cd2c77 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs @@ -38,7 +38,7 @@ declare_lint_pass!(ImplicitSaturatingSub => [IMPLICIT_SATURATING_SUB]); impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { - if in_macro(expr.span) { + if in_macro(cx.tcx.hir().span(expr.hir_id)) { return; } if_chain! { @@ -156,7 +156,7 @@ fn print_lint_and_sugg(cx: &LateContext<'_>, var_name: &str, expr: &Expr<'_>) { span_lint_and_sugg( cx, IMPLICIT_SATURATING_SUB, - expr.span, + cx.tcx.hir().span(expr.hir_id), "implicitly performing saturating subtraction", "try", format!("{} = {}.saturating_sub({});", var_name, var_name, '1'), diff --git a/src/tools/clippy/clippy_lints/src/inconsistent_struct_constructor.rs b/src/tools/clippy/clippy_lints/src/inconsistent_struct_constructor.rs index 4f35e13c85a1c..a43d72ac0eea0 100644 --- a/src/tools/clippy/clippy_lints/src/inconsistent_struct_constructor.rs +++ b/src/tools/clippy/clippy_lints/src/inconsistent_struct_constructor.rs @@ -92,7 +92,7 @@ impl LateLintPass<'_> for InconsistentStructConstructor { fields_snippet.push_str(&last_ident.to_string()); let base_snippet = if let Some(base) = base { - format!(", ..{}", snippet(cx, base.span, "..")) + format!(", ..{}", snippet(cx, cx.tcx.hir().span(base.hir_id), "..")) } else { String::new() }; @@ -106,7 +106,7 @@ impl LateLintPass<'_> for InconsistentStructConstructor { span_lint_and_sugg( cx, INCONSISTENT_STRUCT_CONSTRUCTOR, - expr.span, + cx.tcx.hir().span(expr.hir_id), "inconsistent struct constructor", "try", sugg, diff --git a/src/tools/clippy/clippy_lints/src/indexing_slicing.rs b/src/tools/clippy/clippy_lints/src/indexing_slicing.rs index c919ec097a239..4a2d9a297514b 100644 --- a/src/tools/clippy/clippy_lints/src/indexing_slicing.rs +++ b/src/tools/clippy/clippy_lints/src/indexing_slicing.rs @@ -87,6 +87,7 @@ declare_lint_pass!(IndexingSlicing => [INDEXING_SLICING, OUT_OF_BOUNDS_INDEXING] impl<'tcx> LateLintPass<'tcx> for IndexingSlicing { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { + let expr_span = cx.tcx.hir().span(expr.hir_id); if let ExprKind::Index(ref array, ref index) = &expr.kind { let ty = cx.typeck_results().expr_ty(array).peel_refs(); if let Some(range) = higher::range(index) { @@ -105,7 +106,7 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing { span_lint( cx, OUT_OF_BOUNDS_INDEXING, - range.start.map_or(expr.span, |start| start.span), + range.start.map_or(expr_span, |start| cx.tcx.hir().span(start.hir_id)), "range is out of bounds", ); return; @@ -117,7 +118,7 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing { span_lint( cx, OUT_OF_BOUNDS_INDEXING, - range.end.map_or(expr.span, |end| end.span), + range.end.map_or(expr_span, |end| cx.tcx.hir().span(end.hir_id)), "range is out of bounds", ); return; @@ -138,7 +139,7 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing { (None, None) => return, // [..] is ok. }; - span_lint_and_help(cx, INDEXING_SLICING, expr.span, "slicing may panic", None, help_msg); + span_lint_and_help(cx, INDEXING_SLICING, expr_span, "slicing may panic", None, help_msg); } else { // Catchall non-range index, i.e., [n] or [n << m] if let ty::Array(..) = ty.kind() { @@ -152,7 +153,7 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing { span_lint_and_help( cx, INDEXING_SLICING, - expr.span, + expr_span, "indexing may panic", None, "consider using `.get(n)` or `.get_mut(n)` instead", diff --git a/src/tools/clippy/clippy_lints/src/infinite_iter.rs b/src/tools/clippy/clippy_lints/src/infinite_iter.rs index 7040ac3191f3c..16e9336006f5b 100644 --- a/src/tools/clippy/clippy_lints/src/infinite_iter.rs +++ b/src/tools/clippy/clippy_lints/src/infinite_iter.rs @@ -53,7 +53,7 @@ impl<'tcx> LateLintPass<'tcx> for InfiniteIter { return; }, }; - span_lint(cx, lint, expr.span, msg) + span_lint(cx, lint, cx.tcx.hir().span(expr.hir_id), msg) } } diff --git a/src/tools/clippy/clippy_lints/src/integer_division.rs b/src/tools/clippy/clippy_lints/src/integer_division.rs index 39b4605e72f10..fff2fe674e3bf 100644 --- a/src/tools/clippy/clippy_lints/src/integer_division.rs +++ b/src/tools/clippy/clippy_lints/src/integer_division.rs @@ -36,7 +36,7 @@ impl<'tcx> LateLintPass<'tcx> for IntegerDivision { span_lint_and_help( cx, INTEGER_DIVISION, - expr.span, + cx.tcx.hir().span(expr.hir_id), "integer division", None, "division of integers may cause loss of precision. consider using floats", diff --git a/src/tools/clippy/clippy_lints/src/large_stack_arrays.rs b/src/tools/clippy/clippy_lints/src/large_stack_arrays.rs index 9a448ab125686..486c9df72fde1 100644 --- a/src/tools/clippy/clippy_lints/src/large_stack_arrays.rs +++ b/src/tools/clippy/clippy_lints/src/large_stack_arrays.rs @@ -51,7 +51,7 @@ impl<'tcx> LateLintPass<'tcx> for LargeStackArrays { span_lint_and_help( cx, LARGE_STACK_ARRAYS, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!( "allocating a local array larger than {} bytes", self.maximum_allowed_size @@ -59,7 +59,7 @@ impl<'tcx> LateLintPass<'tcx> for LargeStackArrays { None, &format!( "consider allocating on the heap with `vec!{}.into_boxed_slice()`", - snippet(cx, expr.span, "[...]") + snippet(cx, cx.tcx.hir().span(expr.hir_id), "[...]") ), ); } diff --git a/src/tools/clippy/clippy_lints/src/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs index c1d121b60b6a6..40b8e7769d9cd 100644 --- a/src/tools/clippy/clippy_lints/src/len_zero.rs +++ b/src/tools/clippy/clippy_lints/src/len_zero.rs @@ -155,30 +155,31 @@ impl<'tcx> LateLintPass<'tcx> for LenZero { } fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if expr.span.from_expansion() { + let expr_span = cx.tcx.hir().span(expr.hir_id); + if expr_span.from_expansion() { return; } if let ExprKind::Binary(Spanned { node: cmp, .. }, ref left, ref right) = expr.kind { match cmp { BinOpKind::Eq => { - check_cmp(cx, expr.span, left, right, "", 0); // len == 0 - check_cmp(cx, expr.span, right, left, "", 0); // 0 == len + check_cmp(cx, expr_span, left, right, "", 0); // len == 0 + check_cmp(cx, expr_span, right, left, "", 0); // 0 == len }, BinOpKind::Ne => { - check_cmp(cx, expr.span, left, right, "!", 0); // len != 0 - check_cmp(cx, expr.span, right, left, "!", 0); // 0 != len + check_cmp(cx, expr_span, left, right, "!", 0); // len != 0 + check_cmp(cx, expr_span, right, left, "!", 0); // 0 != len }, BinOpKind::Gt => { - check_cmp(cx, expr.span, left, right, "!", 0); // len > 0 - check_cmp(cx, expr.span, right, left, "", 1); // 1 > len + check_cmp(cx, expr_span, left, right, "!", 0); // len > 0 + check_cmp(cx, expr_span, right, left, "", 1); // 1 > len }, BinOpKind::Lt => { - check_cmp(cx, expr.span, left, right, "", 1); // len < 1 - check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len + check_cmp(cx, expr_span, left, right, "", 1); // len < 1 + check_cmp(cx, expr_span, right, left, "!", 0); // 0 < len }, - BinOpKind::Ge => check_cmp(cx, expr.span, left, right, "!", 1), // len >= 1 - BinOpKind::Le => check_cmp(cx, expr.span, right, left, "!", 1), // 1 <= len + BinOpKind::Ge => check_cmp(cx, expr_span, left, right, "!", 1), // len >= 1 + BinOpKind::Le => check_cmp(cx, expr_span, right, left, "!", 1), // 1 <= len _ => (), } } @@ -364,7 +365,7 @@ fn check_len( format!( "{}{}.is_empty()", op, - snippet_with_applicability(cx, args[0].span, "_", &mut applicability) + snippet_with_applicability(cx, cx.tcx.hir().span(args[0].hir_id), "_", &mut applicability) ), applicability, ); @@ -384,7 +385,7 @@ fn check_empty_expr(cx: &LateContext<'_>, span: Span, lit1: &Expr<'_>, lit2: &Ex format!( "{}{}.is_empty()", op, - snippet_with_applicability(cx, lit1.span, "_", &mut applicability) + snippet_with_applicability(cx, cx.tcx.hir().span(lit1.hir_id), "_", &mut applicability) ), applicability, ); 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 0e1f526b1c59e..6c33894da95bd 100644 --- a/src/tools/clippy/clippy_lints/src/let_if_seq.rs +++ b/src/tools/clippy/clippy_lints/src/let_if_seq.rs @@ -69,7 +69,7 @@ impl<'tcx> LateLintPass<'tcx> for LetIfSeq { if let Some(value) = check_assign(cx, canonical_id, &*then); if !used_visitor.check_expr(value); then { - let span = cx.tcx.hir().span(stmt.hir_id).to(if_.span); + let span = cx.tcx.hir().span(stmt.hir_id).to(cx.tcx.hir().span(if_.hir_id)); let has_interior_mutability = !cx.typeck_results().node_type(canonical_id).is_freeze( cx.tcx.at(span), @@ -107,11 +107,11 @@ impl<'tcx> LateLintPass<'tcx> for LetIfSeq { "let {mut}{name} = if {cond} {{{then} {value} }} else {{{else} {default} }};", mut=mutability, name=ident.name, - cond=snippet(cx, cond.span, "_"), + cond=snippet(cx, cx.tcx.hir().span(cond.hir_id), "_"), then=if then.stmts.len() > 1 { " ..;" } else { "" }, else=if default_multi_stmts { " ..;" } else { "" }, - value=snippet(cx, value.span, ""), - default=snippet(cx, default.span, ""), + value=snippet(cx, cx.tcx.hir().span(value.hir_id), ""), + default=snippet(cx, cx.tcx.hir().span(default.hir_id), ""), ); span_lint_and_then(cx, USELESS_LET_IF_SEQ, diff --git a/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs b/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs index 43e85538f281d..a833bd2bb6415 100644 --- a/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs @@ -12,6 +12,6 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, loop_block: &' } else { "you should either use `panic!()` or add `std::thread::sleep(..);` to the loop body" }; - span_lint_and_help(cx, EMPTY_LOOP, expr.span, msg, None, help); + span_lint_and_help(cx, EMPTY_LOOP, cx.tcx.hir().span(expr.hir_id), msg, None, help); } } diff --git a/src/tools/clippy/clippy_lints/src/loops/explicit_counter_loop.rs b/src/tools/clippy/clippy_lints/src/loops/explicit_counter_loop.rs index efafb52e9dc54..1174f116ad521 100644 --- a/src/tools/clippy/clippy_lints/src/loops/explicit_counter_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/explicit_counter_loop.rs @@ -35,12 +35,12 @@ pub(super) fn check<'tcx>( then { let mut applicability = Applicability::MachineApplicable; - let for_span = get_span_of_entire_for_loop(expr); + let for_span = get_span_of_entire_for_loop(cx, expr); span_lint_and_sugg( cx, EXPLICIT_COUNTER_LOOP, - for_span.with_hi(arg.span.hi()), + for_span.with_hi(cx.tcx.hir().span(arg.hir_id).hi()), &format!("the variable `{}` is used as a loop counter", name), "consider using", format!( diff --git a/src/tools/clippy/clippy_lints/src/loops/explicit_into_iter_loop.rs b/src/tools/clippy/clippy_lints/src/loops/explicit_into_iter_loop.rs index 1d778205a2ad1..c9c7239a83f73 100644 --- a/src/tools/clippy/clippy_lints/src/loops/explicit_into_iter_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/explicit_into_iter_loop.rs @@ -13,11 +13,11 @@ pub(super) fn check(cx: &LateContext<'_>, args: &'hir [Expr<'hir>], arg: &Expr<' } let mut applicability = Applicability::MachineApplicable; - let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability); + let object = snippet_with_applicability(cx, cx.tcx.hir().span(args[0].hir_id), "_", &mut applicability); span_lint_and_sugg( cx, EXPLICIT_INTO_ITER_LOOP, - arg.span, + cx.tcx.hir().span(arg.hir_id), "it is more concise to loop over containers instead of using explicit \ iteration methods", "to write this more concisely, try", diff --git a/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs b/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs index 9683e59a3962d..6b719e7f30aa1 100644 --- a/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs @@ -31,12 +31,12 @@ pub(super) fn check(cx: &LateContext<'_>, args: &[Expr<'_>], arg: &Expr<'_>, met } let mut applicability = Applicability::MachineApplicable; - let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability); + let object = snippet_with_applicability(cx, cx.tcx.hir().span(args[0].hir_id), "_", &mut applicability); let muta = if method_name == "iter_mut" { "mut " } else { "" }; span_lint_and_sugg( cx, EXPLICIT_ITER_LOOP, - arg.span, + cx.tcx.hir().span(arg.hir_id), "it is more concise to loop over references to containers instead of using explicit \ iteration methods", "to write this more concisely, try", diff --git a/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs b/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs index 28acbcd4c9fb7..2dd5cd069f31c 100644 --- a/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs +++ b/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs @@ -18,7 +18,7 @@ pub(super) fn check<'tcx>( if let PatKind::Tuple(ref pat, _) = pat.kind { if pat.len() == 2 { - let arg_span = arg.span; + let arg_span = cx.tcx.hir().span(arg.hir_id); 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(cx, key, body) => (cx.tcx.hir().span(pat[1].hir_id), "value", ty, mutbl), @@ -42,7 +42,7 @@ pub(super) fn check<'tcx>( span_lint_and_then( cx, FOR_KV_MAP, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("you seem to want to iterate on a map's {}s", kind), |diag| { let map = sugg::Sugg::hir(cx, arg, "map"); diff --git a/src/tools/clippy/clippy_lints/src/loops/for_loops_over_fallibles.rs b/src/tools/clippy/clippy_lints/src/loops/for_loops_over_fallibles.rs index 4c239c8bba2d1..0f90b12e39160 100644 --- a/src/tools/clippy/clippy_lints/src/loops/for_loops_over_fallibles.rs +++ b/src/tools/clippy/clippy_lints/src/loops/for_loops_over_fallibles.rs @@ -7,38 +7,39 @@ use rustc_span::symbol::sym; /// Checks for `for` loops over `Option`s and `Result`s. pub(super) fn check(cx: &LateContext<'_>, pat: &Pat<'_>, arg: &Expr<'_>) { let ty = cx.typeck_results().expr_ty(arg); + let arg_span = cx.tcx.hir().span(arg.hir_id); if is_type_diagnostic_item(cx, ty, sym::option_type) { span_lint_and_help( cx, FOR_LOOPS_OVER_FALLIBLES, - arg.span, + arg_span, &format!( "for loop over `{0}`, which is an `Option`. This is more readably written as an \ `if let` statement", - snippet(cx, arg.span, "_") + snippet(cx, arg_span, "_") ), None, &format!( "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`", snippet(cx, cx.tcx.hir().span(pat.hir_id), "_"), - snippet(cx, arg.span, "_") + snippet(cx, arg_span, "_") ), ); } else if is_type_diagnostic_item(cx, ty, sym::result_type) { span_lint_and_help( cx, FOR_LOOPS_OVER_FALLIBLES, - arg.span, + arg_span, &format!( "for loop over `{0}`, which is a `Result`. This is more readably written as an \ `if let` statement", - snippet(cx, arg.span, "_") + snippet(cx, arg_span, "_") ), None, &format!( "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`", snippet(cx, cx.tcx.hir().span(pat.hir_id), "_"), - snippet(cx, arg.span, "_") + snippet(cx, arg_span, "_") ), ); } diff --git a/src/tools/clippy/clippy_lints/src/loops/iter_next_loop.rs b/src/tools/clippy/clippy_lints/src/loops/iter_next_loop.rs index cf78bbc49a362..b9d6aa171f73a 100644 --- a/src/tools/clippy/clippy_lints/src/loops/iter_next_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/iter_next_loop.rs @@ -8,7 +8,7 @@ pub(super) fn check(cx: &LateContext<'_>, arg: &Expr<'_>, expr: &Expr<'_>) -> bo span_lint( cx, ITER_NEXT_LOOP, - expr.span, + cx.tcx.hir().span(expr.hir_id), "you are iterating over `Iterator::next()` which is an Option; this will compile but is \ probably not what you want", ); diff --git a/src/tools/clippy/clippy_lints/src/loops/manual_flatten.rs b/src/tools/clippy/clippy_lints/src/loops/manual_flatten.rs index 3d3ae6f3152a3..428c7934c50ce 100644 --- a/src/tools/clippy/clippy_lints/src/loops/manual_flatten.rs +++ b/src/tools/clippy/clippy_lints/src/loops/manual_flatten.rs @@ -62,13 +62,13 @@ pub(super) fn check<'tcx>( |diag| { let sugg = format!("{}.flatten()", arg_snippet); diag.span_suggestion( - arg.span, + cx.tcx.hir().span(arg.hir_id), "try", sugg, Applicability::MaybeIncorrect, ); diag.span_help( - inner_expr.span, + cx.tcx.hir().span(inner_expr.hir_id), "...and remove the `if let` statement in the for loop", ); } diff --git a/src/tools/clippy/clippy_lints/src/loops/manual_memcpy.rs b/src/tools/clippy/clippy_lints/src/loops/manual_memcpy.rs index 11660a8fe0dfb..79204c4a7aa9c 100644 --- a/src/tools/clippy/clippy_lints/src/loops/manual_memcpy.rs +++ b/src/tools/clippy/clippy_lints/src/loops/manual_memcpy.rs @@ -85,7 +85,7 @@ pub(super) fn check<'tcx>( span_lint_and_sugg( cx, MANUAL_MEMCPY, - get_span_of_entire_for_loop(expr), + get_span_of_entire_for_loop(cx, expr), "it looks like you're manually copying between slices", "try replacing the loop by", big_sugg, @@ -170,8 +170,8 @@ fn build_manual_memcpy_suggestion<'tcx>( let (dst_offset, dst_limit) = print_offset_and_limit(&dst); let (src_offset, src_limit) = print_offset_and_limit(&src); - let dst_base_str = snippet(cx, dst.base.span, "???"); - let src_base_str = snippet(cx, src.base.span, "???"); + let dst_base_str = snippet(cx, cx.tcx.hir().span(dst.base.hir_id), "???"); + let src_base_str = snippet(cx, cx.tcx.hir().span(src.base.hir_id), "???"); let dst = if dst_offset == sugg::EMPTY && dst_limit == sugg::EMPTY { dst_base_str diff --git a/src/tools/clippy/clippy_lints/src/loops/mod.rs b/src/tools/clippy/clippy_lints/src/loops/mod.rs index 65f7aaee1f575..5fa42dab839a4 100644 --- a/src/tools/clippy/clippy_lints/src/loops/mod.rs +++ b/src/tools/clippy/clippy_lints/src/loops/mod.rs @@ -545,14 +545,14 @@ impl<'tcx> LateLintPass<'tcx> for Loops { // we don't want to check expanded macros // this check is not at the top of the function // since higher::for_loop expressions are marked as expansions - if body.span.from_expansion() { + if cx.tcx.hir().span(body.hir_id).from_expansion() { return; } check_for_loop(cx, pat, arg, body, expr, span); } // we don't want to check expanded macros - if expr.span.from_expansion() { + if cx.tcx.hir().span(expr.hir_id).from_expansion() { return; } diff --git a/src/tools/clippy/clippy_lints/src/loops/needless_collect.rs b/src/tools/clippy/clippy_lints/src/loops/needless_collect.rs index 563ed6ff01d67..a7bdcc126b7d9 100644 --- a/src/tools/clippy/clippy_lints/src/loops/needless_collect.rs +++ b/src/tools/clippy/clippy_lints/src/loops/needless_collect.rs @@ -33,7 +33,7 @@ fn check_needless_collect_direct_usage<'tcx>(expr: &'tcx Expr<'_>, cx: &LateCont match_type(cx, ty, &paths::BTREEMAP) || is_type_diagnostic_item(cx, ty, sym::hashmap_type) { if method.ident.name == sym!(len) { - let span = shorten_needless_collect_span(expr); + let span = shorten_needless_collect_span(cx, expr); span_lint_and_sugg( cx, NEEDLESS_COLLECT, @@ -45,7 +45,7 @@ fn check_needless_collect_direct_usage<'tcx>(expr: &'tcx Expr<'_>, cx: &LateCont ); } if method.ident.name == sym!(is_empty) { - let span = shorten_needless_collect_span(expr); + let span = shorten_needless_collect_span(cx, expr); span_lint_and_sugg( cx, NEEDLESS_COLLECT, @@ -57,8 +57,8 @@ fn check_needless_collect_direct_usage<'tcx>(expr: &'tcx Expr<'_>, cx: &LateCont ); } if method.ident.name == sym!(contains) { - let contains_arg = snippet(cx, args[1].span, "??"); - let span = shorten_needless_collect_span(expr); + let contains_arg = snippet(cx, cx.tcx.hir().span(args[1].hir_id), "??"); + let span = shorten_needless_collect_span(cx, expr); span_lint_and_then( cx, NEEDLESS_COLLECT, @@ -101,7 +101,7 @@ fn check_needless_collect_indirect_usage<'tcx>(expr: &'tcx Expr<'_>, cx: &LateCo if is_type_diagnostic_item(cx, ty, sym::vec_type) || is_type_diagnostic_item(cx, ty, sym::vecdeque_type) || match_type(cx, ty, &paths::LINKED_LIST); - if let Some(iter_calls) = detect_iter_and_into_iters(block, *ident); + if let Some(iter_calls) = detect_iter_and_into_iters(cx, block, *ident); if iter_calls.len() == 1; then { let mut used_count_visitor = UsedCountVisitor { @@ -184,12 +184,13 @@ enum IterFunctionKind { Contains(Span), } -struct IterFunctionVisitor { +struct IterFunctionVisitor<'a, 'tcx> { + cx: &'a LateContext<'tcx>, uses: Vec, seen_other: bool, target: Ident, } -impl<'tcx> Visitor<'tcx> for IterFunctionVisitor { +impl<'a, 'tcx> Visitor<'tcx> for IterFunctionVisitor<'a, 'tcx> { fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) { // Check function calls on our collection if_chain! { @@ -201,18 +202,19 @@ impl<'tcx> Visitor<'tcx> for IterFunctionVisitor { let len = sym!(len); let is_empty = sym!(is_empty); let contains = sym!(contains); + let expr_span = self.cx.tcx.hir().span(expr.hir_id); match method_name.ident.name { sym::into_iter => self.uses.push( - IterFunction { func: IterFunctionKind::IntoIter, span: expr.span } + IterFunction { func: IterFunctionKind::IntoIter, span: expr_span } ), name if name == len => self.uses.push( - IterFunction { func: IterFunctionKind::Len, span: expr.span } + IterFunction { func: IterFunctionKind::Len, span: expr_span } ), name if name == is_empty => self.uses.push( - IterFunction { func: IterFunctionKind::IsEmpty, span: expr.span } + IterFunction { func: IterFunctionKind::IsEmpty, span: expr_span } ), name if name == contains => self.uses.push( - IterFunction { func: IterFunctionKind::Contains(args[1].span), span: expr.span } + IterFunction { func: IterFunctionKind::Contains(self.cx.tcx.hir().span(args[1].hir_id)), span: expr_span } ), _ => self.seen_other = true, } @@ -262,8 +264,9 @@ impl<'a, 'tcx> Visitor<'tcx> for UsedCountVisitor<'a, 'tcx> { /// Detect the occurrences of calls to `iter` or `into_iter` for the /// given identifier -fn detect_iter_and_into_iters<'tcx>(block: &'tcx Block<'tcx>, identifier: Ident) -> Option> { +fn detect_iter_and_into_iters<'tcx>(cx: &LateContext<'tcx>, block: &'tcx Block<'tcx>, identifier: Ident) -> Option> { let mut visitor = IterFunctionVisitor { + cx: cx, uses: Vec::new(), target: identifier, seen_other: false, @@ -272,12 +275,12 @@ fn detect_iter_and_into_iters<'tcx>(block: &'tcx Block<'tcx>, identifier: Ident) if visitor.seen_other { None } else { Some(visitor.uses) } } -fn shorten_needless_collect_span(expr: &Expr<'_>) -> Span { +fn shorten_needless_collect_span(cx: &LateContext<'_>, expr: &Expr<'_>) -> Span { if_chain! { if let ExprKind::MethodCall(.., args, _) = &expr.kind; if let ExprKind::MethodCall(_, span, ..) = &args[0].kind; then { - return expr.span.with_lo(span.lo()); + return cx.tcx.hir().span(expr.hir_id).with_lo(span.lo()); } } unreachable!(); diff --git a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs index 83cd12538d79b..8812a68d68064 100644 --- a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs @@ -86,7 +86,7 @@ pub(super) fn check<'tcx>( } else if visitor.indexed_mut.contains(&indexed) && contains_name(indexed, start) { return; } else { - format!(".skip({})", snippet(cx, start.span, "..")) + format!(".skip({})", snippet(cx, cx.tcx.hir().span(start.hir_id), "..")) }; let mut end_is_start_plus_val = false; @@ -119,7 +119,9 @@ pub(super) fn check<'tcx>( let take_expr = sugg::Sugg::hir(cx, take_expr, ""); format!(".take({})", take_expr + sugg::ONE) }, - ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, take_expr.span, "..")), + ast::RangeLimits::HalfOpen => { + format!(".take({})", snippet(cx, cx.tcx.hir().span(take_expr.hir_id), "..")) + }, } } } else { @@ -144,7 +146,7 @@ pub(super) fn check<'tcx>( span_lint_and_then( cx, NEEDLESS_RANGE_LOOP, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("the loop variable `{}` is used to index `{}`", ident.name, indexed), |diag| { multispan_sugg( @@ -153,7 +155,7 @@ pub(super) fn check<'tcx>( vec![ (cx.tcx.hir().span(pat.hir_id), format!("({}, )", ident.name)), ( - arg.span, + cx.tcx.hir().span(arg.hir_id), format!("{}.{}().enumerate(){}{}", indexed, method, method_1, method_2), ), ], @@ -170,13 +172,16 @@ pub(super) fn check<'tcx>( span_lint_and_then( cx, NEEDLESS_RANGE_LOOP, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("the loop variable `{}` is only used to index `{}`", ident.name, indexed), |diag| { multispan_sugg( diag, "consider using an iterator", - vec![(cx.tcx.hir().span(pat.hir_id), "".to_string()), (arg.span, repl)], + vec![ + (cx.tcx.hir().span(pat.hir_id), "".to_string()), + (cx.tcx.hir().span(arg.hir_id), repl), + ], ); }, ); diff --git a/src/tools/clippy/clippy_lints/src/loops/never_loop.rs b/src/tools/clippy/clippy_lints/src/loops/never_loop.rs index 45e1001d75555..b23f449afa426 100644 --- a/src/tools/clippy/clippy_lints/src/loops/never_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/never_loop.rs @@ -7,7 +7,12 @@ use std::iter::{once, Iterator}; pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if let ExprKind::Loop(ref block, _, _, _) = expr.kind { match never_loop_block(block, expr.hir_id) { - NeverLoopResult::AlwaysBreak => span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops"), + NeverLoopResult::AlwaysBreak => span_lint( + cx, + NEVER_LOOP, + cx.tcx.hir().span(expr.hir_id), + "this loop never actually loops", + ), NeverLoopResult::MayContinueMainLoop | NeverLoopResult::Otherwise => (), } } diff --git a/src/tools/clippy/clippy_lints/src/loops/same_item_push.rs b/src/tools/clippy/clippy_lints/src/loops/same_item_push.rs index f3585830e4ae3..737c5e174cf2b 100644 --- a/src/tools/clippy/clippy_lints/src/loops/same_item_push.rs +++ b/src/tools/clippy/clippy_lints/src/loops/same_item_push.rs @@ -18,13 +18,13 @@ pub(super) fn check<'tcx>( _: &'tcx Expr<'_>, ) { fn emit_lint(cx: &LateContext<'_>, vec: &Expr<'_>, pushed_item: &Expr<'_>) { - let vec_str = snippet_with_macro_callsite(cx, vec.span, ""); - let item_str = snippet_with_macro_callsite(cx, pushed_item.span, ""); + let vec_str = snippet_with_macro_callsite(cx, cx.tcx.hir().span(vec.hir_id), ""); + let item_str = snippet_with_macro_callsite(cx, cx.tcx.hir().span(pushed_item.hir_id), ""); span_lint_and_help( cx, SAME_ITEM_PUSH, - vec.span, + cx.tcx.hir().span(vec.hir_id), "it looks like the same item is being pushed into this Vec", None, &format!( diff --git a/src/tools/clippy/clippy_lints/src/loops/single_element_loop.rs b/src/tools/clippy/clippy_lints/src/loops/single_element_loop.rs index c57a4063d8b7f..32313060b4695 100644 --- a/src/tools/clippy/clippy_lints/src/loops/single_element_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/single_element_loop.rs @@ -22,7 +22,7 @@ pub(super) fn check<'tcx>( if !block.stmts.is_empty(); then { - let for_span = get_span_of_entire_for_loop(expr); + let for_span = get_span_of_entire_for_loop(cx, expr); let mut block_str = snippet(cx, cx.tcx.hir().span(block.hir_id), "..").into_owned(); block_str.remove(0); block_str.pop(); diff --git a/src/tools/clippy/clippy_lints/src/loops/utils.rs b/src/tools/clippy/clippy_lints/src/loops/utils.rs index 9e38e17719aad..576e27d42a2d5 100644 --- a/src/tools/clippy/clippy_lints/src/loops/utils.rs +++ b/src/tools/clippy/clippy_lints/src/loops/utils.rs @@ -303,11 +303,11 @@ impl<'tcx> Visitor<'tcx> for LoopNestVisitor { } // this function assumes the given expression is a `for` loop. -pub(super) fn get_span_of_entire_for_loop(expr: &Expr<'_>) -> Span { +pub(super) fn get_span_of_entire_for_loop(cx: &LateContext<'_>, expr: &Expr<'_>) -> Span { // for some reason this is the only way to get the `Span` // of the entire `for` loop if let ExprKind::Match(_, arms, _) = &expr.kind { - arms[0].body.span + cx.tcx.hir().span(arms[0].body.hir_id) } else { unreachable!() } diff --git a/src/tools/clippy/clippy_lints/src/loops/while_immutable_condition.rs b/src/tools/clippy/clippy_lints/src/loops/while_immutable_condition.rs index 05e0a7225631c..2b68545f42564 100644 --- a/src/tools/clippy/clippy_lints/src/loops/while_immutable_condition.rs +++ b/src/tools/clippy/clippy_lints/src/loops/while_immutable_condition.rs @@ -45,7 +45,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, cond: &'tcx Expr<'_>, expr: &' span_lint_and_then( cx, WHILE_IMMUTABLE_CONDITION, - cond.span, + cx.tcx.hir().span(cond.hir_id), "variables in the condition are not mutated in the loop body", |diag| { diag.note("this may lead to an infinite or to a never running loop"); diff --git a/src/tools/clippy/clippy_lints/src/loops/while_let_loop.rs b/src/tools/clippy/clippy_lints/src/loops/while_let_loop.rs index 5a38a4216eca8..f51624b9da6c4 100644 --- a/src/tools/clippy/clippy_lints/src/loops/while_let_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/while_let_loop.rs @@ -19,7 +19,7 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, loop_block: &' && arms[1].guard.is_none() && is_simple_break_expr(&arms[1].body) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), cx.tcx.hir().span(expr.hir_id)) { return; } @@ -32,7 +32,7 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, loop_block: &' span_lint_and_sugg( cx, WHILE_LET_LOOP, - expr.span, + cx.tcx.hir().span(expr.hir_id), "this loop could be written as a `while let` loop", "try", format!( @@ -43,7 +43,12 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, loop_block: &' "..", &mut applicability ), - snippet_with_applicability(cx, matchexpr.span, "..", &mut applicability), + snippet_with_applicability( + cx, + cx.tcx.hir().span(matchexpr.hir_id), + "..", + &mut applicability + ), ), applicability, ); diff --git a/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs b/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs index bb9ebf22158d0..18c04818a50e2 100644 --- a/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs +++ b/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs @@ -45,7 +45,8 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { && !is_nested(cx, expr, &method_args[0])) { let mut applicability = Applicability::MachineApplicable; - let iterator = snippet_with_applicability(cx, method_args[0].span, "_", &mut applicability); + let iterator = + snippet_with_applicability(cx, cx.tcx.hir().span(method_args[0].hir_id), "_", &mut applicability); let loop_var = if pat_args.is_empty() { "_".to_string() } else { @@ -55,7 +56,10 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { span_lint_and_sugg( cx, WHILE_LET_ON_ITERATOR, - expr.span.with_hi(match_expr.span.hi()), + cx.tcx + .hir() + .span(expr.hir_id) + .with_hi(cx.tcx.hir().span(match_expr.hir_id).hi()), "this loop could be written as a `for` loop", "try", format!("for {} in {}", loop_var, iterator), diff --git a/src/tools/clippy/clippy_lints/src/macro_use.rs b/src/tools/clippy/clippy_lints/src/macro_use.rs index 92d96560a1e01..20336d1604b15 100644 --- a/src/tools/clippy/clippy_lints/src/macro_use.rs +++ b/src/tools/clippy/clippy_lints/src/macro_use.rs @@ -134,8 +134,9 @@ impl<'tcx> LateLintPass<'tcx> for MacroUseImports { } } fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) { - if in_macro(expr.span) { - self.push_unique_macro(cx, expr.span); + let expr_span = cx.tcx.hir().span(expr.hir_id); + if in_macro(expr_span) { + self.push_unique_macro(cx, expr_span); } } fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &hir::Stmt<'_>) { diff --git a/src/tools/clippy/clippy_lints/src/main_recursion.rs b/src/tools/clippy/clippy_lints/src/main_recursion.rs index 1b274c79d3820..2aded19e41f13 100644 --- a/src/tools/clippy/clippy_lints/src/main_recursion.rs +++ b/src/tools/clippy/clippy_lints/src/main_recursion.rs @@ -50,8 +50,8 @@ impl LateLintPass<'_> for MainRecursion { span_lint_and_help( cx, MAIN_RECURSION, - func.span, - &format!("recursing into entrypoint `{}`", snippet(cx, func.span, "main")), + cx.tcx.hir().span(func.hir_id), + &format!("recursing into entrypoint `{}`", snippet(cx, cx.tcx.hir().span(func.hir_id), "main")), None, "consider using another function for this recursion" ) 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 7eef59cd15b04..7c31b37af3034 100644 --- a/src/tools/clippy/clippy_lints/src/manual_async_fn.rs +++ b/src/tools/clippy/clippy_lints/src/manual_async_fn.rs @@ -81,7 +81,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualAsyncFn { ); let block_span = cx.tcx.hir().span(block.hir_id); - let body_snip = snippet_block(cx, closure_body.value.span, "..", Some(block_span)); + let body_snip = snippet_block(cx, cx.tcx.hir().span(closure_body.value.hir_id), "..", Some(block_span)); diag.span_suggestion( block_span, "move the body of the async block to the enclosing function", diff --git a/src/tools/clippy/clippy_lints/src/manual_map.rs b/src/tools/clippy/clippy_lints/src/manual_map.rs index 5c0b51ad47c31..3566845a84fbb 100644 --- a/src/tools/clippy/clippy_lints/src/manual_map.rs +++ b/src/tools/clippy/clippy_lints/src/manual_map.rs @@ -51,7 +51,7 @@ declare_lint_pass!(ManualMap => [MANUAL_MAP]); impl LateLintPass<'_> for ManualMap { #[allow(clippy::too_many_lines)] fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), cx.tcx.hir().span(expr.hir_id)) { return; } @@ -66,7 +66,7 @@ impl LateLintPass<'_> for ManualMap { return; } - let expr_ctxt = expr.span.ctxt(); + let expr_ctxt = cx.tcx.hir().span(expr.hir_id).ctxt(); let (some_expr, some_pat, pat_ref_count, is_wild_none) = match ( try_parse_pattern(cx, arm1.pat, expr_ctxt), try_parse_pattern(cx, arm2.pat, expr_ctxt), @@ -129,18 +129,22 @@ impl LateLintPass<'_> for ManualMap { // Remove address-of expressions from the scrutinee. Either `as_ref` will be called, or // it's being passed by value. let scrutinee = peel_hir_expr_refs(scrutinee).0; - let scrutinee_str = snippet_with_context(cx, scrutinee.span, expr_ctxt, "..", &mut app); let scrutinee_str = - if scrutinee.span.ctxt() == expr.span.ctxt() && scrutinee.precedence().order() < PREC_POSTFIX { - format!("({})", scrutinee_str) - } else { - scrutinee_str.into() - }; + snippet_with_context(cx, cx.tcx.hir().span(scrutinee.hir_id), expr_ctxt, "..", &mut app); + let scrutinee_str = if cx.tcx.hir().span(scrutinee.hir_id).ctxt() == expr_ctxt + && scrutinee.precedence().order() < PREC_POSTFIX + { + format!("({})", scrutinee_str) + } else { + scrutinee_str.into() + }; let body_str = if let PatKind::Binding(annotation, _, some_binding, None) = some_pat.kind { match can_pass_as_func(cx, some_binding, some_expr) { - Some(func) if func.span.ctxt() == some_expr.span.ctxt() => { - snippet_with_applicability(cx, func.span, "..", &mut app).into_owned() + Some(func) + if cx.tcx.hir().span(func.hir_id).ctxt() == cx.tcx.hir().span(some_expr.hir_id).ctxt() => + { + snippet_with_applicability(cx, cx.tcx.hir().span(func.hir_id), "..", &mut app).into_owned() }, _ => { if match_var(some_expr, some_binding.name) @@ -160,7 +164,7 @@ impl LateLintPass<'_> for ManualMap { "|{}{}| {}", annotation, some_binding, - snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app) + snippet_with_context(cx, cx.tcx.hir().span(some_expr.hir_id), expr_ctxt, "..", &mut app) ) }, } @@ -179,7 +183,7 @@ impl LateLintPass<'_> for ManualMap { span_lint_and_sugg( cx, MANUAL_MAP, - expr.span, + cx.tcx.hir().span(expr.hir_id), "manual implementation of `Option::map`", "try this", format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str), @@ -299,7 +303,7 @@ fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ctxt: SyntaxConte .. }, [arg], - ) if ctxt == expr.span.ctxt() => { + ) if ctxt == cx.tcx.hir().span(expr.hir_id).ctxt() => { if match_def_path(cx, path.res.opt_def_id()?, &paths::OPTION_SOME) { Some(arg) } else { diff --git a/src/tools/clippy/clippy_lints/src/manual_ok_or.rs b/src/tools/clippy/clippy_lints/src/manual_ok_or.rs index efb05b8ffdf4f..11566cda95fb4 100644 --- a/src/tools/clippy/clippy_lints/src/manual_ok_or.rs +++ b/src/tools/clippy/clippy_lints/src/manual_ok_or.rs @@ -40,7 +40,7 @@ declare_lint_pass!(ManualOkOr => [MANUAL_OK_OR]); impl LateLintPass<'_> for ManualOkOr { fn check_expr(&mut self, cx: &LateContext<'tcx>, scrutinee: &'tcx Expr<'tcx>) { - if in_external_macro(cx.sess(), scrutinee.span) { + if in_external_macro(cx.sess(), cx.tcx.hir().span(scrutinee.hir_id)) { return; } @@ -55,16 +55,16 @@ impl LateLintPass<'_> for ManualOkOr { if is_ok_wrapping(cx, &args[2]); if let ExprKind::Call(Expr { kind: ExprKind::Path(err_path), .. }, &[ref err_arg]) = or_expr.kind; if match_qpath(err_path, &paths::RESULT_ERR); - if let Some(method_receiver_snippet) = snippet_opt(cx, method_receiver.span); - if let Some(err_arg_snippet) = snippet_opt(cx, err_arg.span); - if let Some(indent) = indent_of(cx, scrutinee.span); + if let Some(method_receiver_snippet) = snippet_opt(cx, cx.tcx.hir().span(method_receiver.hir_id)); + if let Some(err_arg_snippet) = snippet_opt(cx, cx.tcx.hir().span(err_arg.hir_id)); + if let Some(indent) = indent_of(cx, cx.tcx.hir().span(scrutinee.hir_id)); then { let reindented_err_arg_snippet = reindent_multiline(err_arg_snippet.into(), true, Some(indent + 4)); span_lint_and_sugg( cx, MANUAL_OK_OR, - scrutinee.span, + cx.tcx.hir().span(scrutinee.hir_id), "this pattern reimplements `Option::ok_or`", "replace with", format!( diff --git a/src/tools/clippy/clippy_lints/src/manual_strip.rs b/src/tools/clippy/clippy_lints/src/manual_strip.rs index 42a92104a4919..5fe3d6e46e016 100644 --- a/src/tools/clippy/clippy_lints/src/manual_strip.rs +++ b/src/tools/clippy/clippy_lints/src/manual_strip.rs @@ -114,7 +114,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualStrip { StripKind::Suffix => "suffix", }; - let test_span = expr.span.until(then.span); + let test_span = cx.tcx.hir().span(expr.hir_id).until(cx.tcx.hir().span(then.hir_id)); span_lint_and_then(cx, MANUAL_STRIP, strippings[0], &format!("stripping a {} manually", kind_word), |diag| { diag.span_note(test_span, &format!("the {} was tested here", kind_word)); multispan_sugg( @@ -122,9 +122,9 @@ impl<'tcx> LateLintPass<'tcx> for ManualStrip { &format!("try using the `strip_{}` method", kind_word), vec![(test_span, format!("if let Some() = {}.strip_{}({}) ", - snippet(cx, target_arg.span, ".."), + snippet(cx, cx.tcx.hir().span(target_arg.hir_id), ".."), kind_word, - snippet(cx, pattern.span, "..")))] + snippet(cx, cx.tcx.hir().span(pattern.hir_id), "..")))] .into_iter().chain(strippings.into_iter().map(|span| (span, "".into()))), ) }); @@ -226,7 +226,7 @@ fn find_stripping<'tcx>( match (self.strip_kind, start, end) { (StripKind::Prefix, Some(start), None) => { if eq_pattern_length(self.cx, self.pattern, start) { - self.results.push(ex.span); + self.results.push(self.cx.tcx.hir().span(ex.hir_id)); return; } }, @@ -238,7 +238,7 @@ fn find_stripping<'tcx>( if self.cx.qpath_res(left_path, left_arg.hir_id) == self.target; if eq_pattern_length(self.cx, self.pattern, right); then { - self.results.push(ex.span); + self.results.push(self.cx.tcx.hir().span(ex.hir_id)); return; } } diff --git a/src/tools/clippy/clippy_lints/src/manual_unwrap_or.rs b/src/tools/clippy/clippy_lints/src/manual_unwrap_or.rs index b452225b5db6c..545f107eeeb93 100644 --- a/src/tools/clippy/clippy_lints/src/manual_unwrap_or.rs +++ b/src/tools/clippy/clippy_lints/src/manual_unwrap_or.rs @@ -42,7 +42,7 @@ declare_lint_pass!(ManualUnwrapOr => [MANUAL_UNWRAP_OR]); impl LateLintPass<'_> for ManualUnwrapOr { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), cx.tcx.hir().span(expr.hir_id)) { return; } lint_manual_unwrap_or(cx, expr); @@ -65,7 +65,7 @@ impl Case { } fn lint_manual_unwrap_or<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { - fn applicable_or_arm<'a>(arms: &'a [Arm<'a>]) -> Option<&'a Arm<'a>> { + fn applicable_or_arm<'a>(cx: &LateContext<'_>, arms: &'a [Arm<'a>]) -> Option<&'a Arm<'a>> { if_chain! { if arms.len() == 2; if arms.iter().all(|arm| arm.guard.is_none()); @@ -84,7 +84,7 @@ fn lint_manual_unwrap_or<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { || utils::match_qpath(unwrap_qpath, &utils::paths::RESULT_OK); if let PatKind::Binding(_, binding_hir_id, ..) = unwrap_pat.kind; if path_to_local_id(unwrap_arm.body, binding_hir_id); - if !utils::usage::contains_return_break_continue_macro(or_arm.body); + if !utils::usage::contains_return_break_continue_macro(cx, or_arm.body); then { Some(or_arm) } else { @@ -103,16 +103,16 @@ fn lint_manual_unwrap_or<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { } else { None }; - if let Some(or_arm) = applicable_or_arm(match_arms); - if let Some(or_body_snippet) = utils::snippet_opt(cx, or_arm.body.span); - if let Some(indent) = utils::indent_of(cx, expr.span); + if let Some(or_arm) = applicable_or_arm(cx, match_arms); + if let Some(or_body_snippet) = utils::snippet_opt(cx, cx.tcx.hir().span(or_arm.body.hir_id)); + if let Some(indent) = utils::indent_of(cx, cx.tcx.hir().span(expr.hir_id)); if constant_simple(cx, cx.typeck_results(), or_arm.body).is_some(); then { let reindented_or_body = utils::reindent_multiline(or_body_snippet.into(), true, Some(indent)); utils::span_lint_and_sugg( cx, - MANUAL_UNWRAP_OR, expr.span, + MANUAL_UNWRAP_OR, cx.tcx.hir().span(expr.hir_id), &format!("this pattern reimplements `{}`", case.unwrap_fn_path()), "replace with", format!( diff --git a/src/tools/clippy/clippy_lints/src/map_clone.rs b/src/tools/clippy/clippy_lints/src/map_clone.rs index 4b685c09a0548..7fffe16f07397 100644 --- a/src/tools/clippy/clippy_lints/src/map_clone.rs +++ b/src/tools/clippy/clippy_lints/src/map_clone.rs @@ -46,7 +46,7 @@ declare_lint_pass!(MapClone => [MAP_CLONE]); impl<'tcx> LateLintPass<'tcx> for MapClone { fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) { - if e.span.from_expansion() { + if cx.tcx.hir().span(e.hir_id).from_expansion() { return; } @@ -65,7 +65,7 @@ impl<'tcx> LateLintPass<'tcx> for MapClone { hir::BindingAnnotation::Unannotated, .., name, None ) = inner.kind { if ident_eq(name, closure_expr) { - lint(cx, e.span, args[0].span, true); + lint(cx, cx.tcx.hir().span(e.hir_id), cx.tcx.hir().span(args[0].hir_id), true); } }, hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, .., name, None) => { @@ -73,7 +73,7 @@ impl<'tcx> LateLintPass<'tcx> for MapClone { hir::ExprKind::Unary(hir::UnOp::Deref, ref inner) => { if ident_eq(name, inner) { if let ty::Ref(.., Mutability::Not) = cx.typeck_results().expr_ty(inner).kind() { - lint(cx, e.span, args[0].span, true); + lint(cx, cx.tcx.hir().span(e.hir_id), cx.tcx.hir().span(args[0].hir_id), true); } } }, @@ -90,10 +90,10 @@ impl<'tcx> LateLintPass<'tcx> for MapClone { if let ty::Ref(_, ty, mutability) = obj_ty.kind() { if matches!(mutability, Mutability::Not) { let copy = is_copy(cx, ty); - lint(cx, e.span, args[0].span, copy); + lint(cx, cx.tcx.hir().span(e.hir_id), cx.tcx.hir().span(args[0].hir_id), copy); } } else { - lint_needless_cloning(cx, e.span, args[0].span); + lint_needless_cloning(cx, cx.tcx.hir().span(e.hir_id), cx.tcx.hir().span(args[0].hir_id)); } } }, diff --git a/src/tools/clippy/clippy_lints/src/map_err_ignore.rs b/src/tools/clippy/clippy_lints/src/map_err_ignore.rs index 76fe8e776eafd..4924cb51cae8a 100644 --- a/src/tools/clippy/clippy_lints/src/map_err_ignore.rs +++ b/src/tools/clippy/clippy_lints/src/map_err_ignore.rs @@ -108,7 +108,7 @@ declare_lint_pass!(MapErrIgnore => [MAP_ERR_IGNORE]); impl<'tcx> LateLintPass<'tcx> for MapErrIgnore { // do not try to lint if this is from a macro or desugaring fn check_expr(&mut self, cx: &LateContext<'_>, e: &Expr<'_>) { - if e.span.from_expansion() { + if cx.tcx.hir().span(e.hir_id).from_expansion() { return; } diff --git a/src/tools/clippy/clippy_lints/src/map_identity.rs b/src/tools/clippy/clippy_lints/src/map_identity.rs index 9f9c108a85a05..acd5f8f7ab1b0 100644 --- a/src/tools/clippy/clippy_lints/src/map_identity.rs +++ b/src/tools/clippy/clippy_lints/src/map_identity.rs @@ -36,7 +36,7 @@ declare_lint_pass!(MapIdentity => [MAP_IDENTITY]); impl<'tcx> LateLintPass<'tcx> for MapIdentity { fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { - if expr.span.from_expansion() { + if cx.tcx.hir().span(expr.hir_id).from_expansion() { return; } @@ -47,7 +47,7 @@ impl<'tcx> LateLintPass<'tcx> for MapIdentity { span_lint_and_sugg( cx, MAP_IDENTITY, - expr.span.trim_start(caller.span).unwrap(), + cx.tcx.hir().span(expr.hir_id).trim_start(cx.tcx.hir().span(caller.hir_id)).unwrap(), "unnecessary map of the identity function", "remove the call to `map`", String::new(), 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 8a2e55fb36c6e..f9673b06df781 100644 --- a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs +++ b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs @@ -128,7 +128,7 @@ fn reduce_unit_expression<'a>(cx: &LateContext<'_>, expr: &'a hir::Expr<'_>) -> match expr.kind { hir::ExprKind::Call(_, _) | hir::ExprKind::MethodCall(_, _, _, _) => { // Calls can't be reduced any more - Some(expr.span) + Some(cx.tcx.hir().span(expr.hir_id)) }, hir::ExprKind::Block(ref block, _) => { match (block.stmts, block.expr.as_ref()) { @@ -142,7 +142,7 @@ fn reduce_unit_expression<'a>(cx: &LateContext<'_>, expr: &'a hir::Expr<'_>) -> // reduce `{ X; }` to `X` or `X;` match inner_stmt.kind { hir::StmtKind::Local(ref local) => Some(cx.tcx.hir().span(local.hir_id)), - hir::StmtKind::Expr(ref e) => Some(e.span), + hir::StmtKind::Expr(ref e) => Some(cx.tcx.hir().span(e.hir_id)), hir::StmtKind::Semi(..) => Some(cx.tcx.hir().span(inner_stmt.hir_id)), hir::StmtKind::Item(..) => None, } @@ -189,8 +189,8 @@ fn unit_closure<'tcx>( /// Anything else will return `a`. fn let_binding_name(cx: &LateContext<'_>, var_arg: &hir::Expr<'_>) -> String { match &var_arg.kind { - hir::ExprKind::Field(_, _) => snippet(cx, var_arg.span, "_").replace(".", "_"), - hir::ExprKind::Path(_) => format!("_{}", snippet(cx, var_arg.span, "")), + hir::ExprKind::Field(_, _) => snippet(cx, cx.tcx.hir().span(var_arg.hir_id), "_").replace(".", "_"), + hir::ExprKind::Path(_) => format!("_{}", snippet(cx, cx.tcx.hir().span(var_arg.hir_id), "")), _ => "a".to_string(), } } @@ -222,24 +222,24 @@ fn lint_map_unit_fn(cx: &LateContext<'_>, stmt: &hir::Stmt<'_>, expr: &hir::Expr let suggestion = format!( "if let {0}({binding}) = {1} {{ {2}({binding}) }}", variant, - snippet(cx, var_arg.span, "_"), - snippet(cx, fn_arg.span, "_"), + snippet(cx, cx.tcx.hir().span(var_arg.hir_id), "_"), + snippet(cx, cx.tcx.hir().span(fn_arg.hir_id), "_"), binding = let_binding_name(cx, var_arg) ); - span_lint_and_then(cx, lint, expr.span, &msg, |diag| { + span_lint_and_then(cx, lint, cx.tcx.hir().span(expr.hir_id), &msg, |diag| { 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); - span_lint_and_then(cx, lint, expr.span, &msg, |diag| { + span_lint_and_then(cx, lint, cx.tcx.hir().span(expr.hir_id), &msg, |diag| { if let Some(reduced_expr_span) = reduce_unit_expression(cx, closure_expr) { let suggestion = format!( "if let {0}({1}) = {2} {{ {3} }}", variant, snippet(cx, cx.tcx.hir().span(binding.pat.hir_id), "_"), - snippet(cx, var_arg.span, "_"), + snippet(cx, cx.tcx.hir().span(var_arg.hir_id), "_"), snippet(cx, reduced_expr_span, "_") ); diag.span_suggestion( @@ -253,7 +253,7 @@ fn lint_map_unit_fn(cx: &LateContext<'_>, stmt: &hir::Stmt<'_>, expr: &hir::Expr "if let {0}({1}) = {2} {{ ... }}", variant, snippet(cx, cx.tcx.hir().span(binding.pat.hir_id), "_"), - snippet(cx, var_arg.span, "_"), + snippet(cx, cx.tcx.hir().span(var_arg.hir_id), "_"), ); diag.span_suggestion(stmt_span, "try this", suggestion, Applicability::HasPlaceholders); } @@ -268,7 +268,7 @@ impl<'tcx> LateLintPass<'tcx> for MapUnit { } if let hir::StmtKind::Semi(ref expr) = stmt.kind { - if let Some(arglists) = method_chain_args(expr, &["map"]) { + if let Some(arglists) = method_chain_args(cx, expr, &["map"]) { lint_map_unit_fn(cx, stmt, expr, arglists[0]); } } diff --git a/src/tools/clippy/clippy_lints/src/match_on_vec_items.rs b/src/tools/clippy/clippy_lints/src/match_on_vec_items.rs index 086dae9422f9b..efce0ed10fa36 100644 --- a/src/tools/clippy/clippy_lints/src/match_on_vec_items.rs +++ b/src/tools/clippy/clippy_lints/src/match_on_vec_items.rs @@ -48,7 +48,7 @@ declare_lint_pass!(MatchOnVecItems => [MATCH_ON_VEC_ITEMS]); impl<'tcx> LateLintPass<'tcx> for MatchOnVecItems { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { if_chain! { - if !in_external_macro(cx.sess(), expr.span); + if !in_external_macro(cx.sess(), cx.tcx.hir().span(expr.hir_id)); if let ExprKind::Match(ref match_expr, _, MatchSource::Normal) = expr.kind; if let Some(idx_expr) = is_vec_indexing(cx, match_expr); if let ExprKind::Index(vec, idx) = idx_expr.kind; @@ -59,13 +59,13 @@ impl<'tcx> LateLintPass<'tcx> for MatchOnVecItems { span_lint_and_sugg( cx, MATCH_ON_VEC_ITEMS, - match_expr.span, + cx.tcx.hir().span(match_expr.hir_id), "indexing into a vector may panic", "try this", format!( "{}.get({})", - snippet(cx, vec.span, ".."), - snippet(cx, idx.span, "..") + snippet(cx, cx.tcx.hir().span(vec.hir_id), ".."), + snippet(cx, cx.tcx.hir().span(idx.hir_id), "..") ), Applicability::MaybeIncorrect ); diff --git a/src/tools/clippy/clippy_lints/src/matches.rs b/src/tools/clippy/clippy_lints/src/matches.rs index cf8d157c4fb00..763639c6542d1 100644 --- a/src/tools/clippy/clippy_lints/src/matches.rs +++ b/src/tools/clippy/clippy_lints/src/matches.rs @@ -573,7 +573,7 @@ const MATCH_LIKE_MATCHES_MACRO_MSRV: RustcVersion = RustcVersion::new(1, 42, 0); impl<'tcx> LateLintPass<'tcx> for Matches { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if in_external_macro(cx.sess(), expr.span) || in_macro(expr.span) { + if in_external_macro(cx.sess(), cx.tcx.hir().span(expr.hir_id)) || in_macro(cx.tcx.hir().span(expr.hir_id)) { return; } @@ -675,7 +675,7 @@ impl<'tcx> LateLintPass<'tcx> for Matches { #[rustfmt::skip] fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) { if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() { - if in_macro(expr.span) { + if in_macro(cx.tcx.hir().span(expr.hir_id)) { // Don't lint match expressions present in // macro_rules! block return; @@ -729,7 +729,10 @@ fn report_single_match_single_pattern( ) { let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH }; let els_str = els.map_or(String::new(), |els| { - format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span))) + format!( + " else {}", + expr_block(cx, els, None, "..", Some(cx.tcx.hir().span(expr.hir_id))) + ) }); let (msg, sugg) = if_chain! { @@ -757,11 +760,11 @@ fn report_single_match_single_pattern( let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`"; let sugg = format!( "if {} == {}{} {}{}", - snippet(cx, ex.span, ".."), + snippet(cx, cx.tcx.hir().span(ex.hir_id), ".."), // PartialEq for different reference counts may not exist. "&".repeat(ref_count_diff), snippet(cx, cx.tcx.hir().span(arms[0].pat.hir_id), ".."), - expr_block(cx, &arms[0].body, None, "..", Some(expr.span)), + expr_block(cx, &arms[0].body, None, "..", Some(cx.tcx.hir().span(expr.hir_id))), els_str, ); (msg, sugg) @@ -770,8 +773,8 @@ fn report_single_match_single_pattern( let sugg = format!( "if let {} = {} {}{}", 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)), + snippet(cx, cx.tcx.hir().span(ex.hir_id), ".."), + expr_block(cx, &arms[0].body, None, "..", Some(cx.tcx.hir().span(expr.hir_id))), els_str, ); (msg, sugg) @@ -781,7 +784,7 @@ fn report_single_match_single_pattern( span_lint_and_sugg( cx, lint, - expr.span, + cx.tcx.hir().span(expr.hir_id), msg, "try this", sugg, @@ -831,12 +834,13 @@ fn check_single_match_opt_like( } fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) { + let expr_span = cx.tcx.hir().span(expr.hir_id); // Type of expression is `bool`. if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool { span_lint_and_then( cx, MATCH_BOOL, - expr.span, + expr_span, "you seem to be trying to match on a boolean expression", move |diag| { if arms.len() == 2 { @@ -859,21 +863,21 @@ fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) { (false, false) => Some(format!( "if {} {} else {}", - snippet(cx, ex.span, "b"), - expr_block(cx, true_expr, None, "..", Some(expr.span)), - expr_block(cx, false_expr, None, "..", Some(expr.span)) + snippet(cx, cx.tcx.hir().span(ex.hir_id), "b"), + expr_block(cx, true_expr, None, "..", Some(expr_span)), + expr_block(cx, false_expr, None, "..", Some(expr_span)) )), (false, true) => Some(format!( "if {} {}", - snippet(cx, ex.span, "b"), - expr_block(cx, true_expr, None, "..", Some(expr.span)) + snippet(cx, cx.tcx.hir().span(ex.hir_id), "b"), + expr_block(cx, true_expr, None, "..", Some(expr_span)) )), (true, false) => { let test = Sugg::hir(cx, ex, ".."); Some(format!( "if {} {}", !test, - expr_block(cx, false_expr, None, "..", Some(expr.span)) + expr_block(cx, false_expr, None, "..", Some(expr_span)) )) }, (true, true) => None, @@ -881,7 +885,7 @@ fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: if let Some(sugg) = sugg { diag.span_suggestion( - expr.span, + expr_span, "consider using an `if`/`else` expression", sugg, Applicability::HasPlaceholders, @@ -1070,7 +1074,8 @@ fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) 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() + let exp_span = cx.tcx.hir().span(exp.hir_id); + is_expn_of(exp_span, "panic").is_some() && is_expn_of(exp_span, "unreachable").is_none() }, (&None, 1, Some(stmt)) => { let stmt_span = cx.tcx.hir().span(stmt.hir_id); @@ -1084,14 +1089,14 @@ fn check_match_ref_pats(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], e if has_only_ref_pats(arms) { let mut suggs = Vec::with_capacity(arms.len() + 1); let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind { - let span = ex.span.source_callsite(); + let span = cx.tcx.hir().span(ex.hir_id).source_callsite(); suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string())); ( "you don't need to add `&` to both the expression and the patterns", "try", ) } else { - let span = ex.span.source_callsite(); + let span = cx.tcx.hir().span(ex.hir_id).source_callsite(); suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string())); ( "you don't need to add `&` to all patterns", @@ -1110,8 +1115,8 @@ fn check_match_ref_pats(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], e } })); - span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| { - if !expr.span.from_expansion() { + span_lint_and_then(cx, MATCH_REF_PATS, cx.tcx.hir().span(expr.hir_id), title, |diag| { + if !cx.tcx.hir().span(expr.hir_id).from_expansion() { multispan_sugg(diag, msg, suggs); } }); @@ -1155,12 +1160,12 @@ fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], exp span_lint_and_sugg( cx, MATCH_AS_REF, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("use `{}()` instead", suggestion), "try this", format!( "{}.{}(){}", - snippet_with_applicability(cx, ex.span, "_", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(ex.hir_id), "_", &mut applicability), suggestion, cast, ), @@ -1230,7 +1235,7 @@ fn find_matches_sugg(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr .join(" | ") }; let pat_and_guard = if let Some(Guard::If(g)) = if_guard { - format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability)) + format!("{} if {}", pat, snippet_with_applicability(cx, cx.tcx.hir().span(g.hir_id), "..", &mut applicability)) } else { pat }; @@ -1245,13 +1250,13 @@ fn find_matches_sugg(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr span_lint_and_sugg( cx, MATCH_LIKE_MATCHES_MACRO, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("{} expression looks like `matches!` macro", if desugared { "if let .. else" } else { "match" }), "try this", format!( "{}matches!({}, {})", if b0 { "" } else { "!" }, - snippet_with_applicability(cx, ex_new.span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(ex_new.hir_id), "..", &mut applicability), pat_and_guard, ), applicability, @@ -1291,7 +1296,8 @@ fn find_bool_lit(ex: &ExprKind<'_>, desugared: bool) -> Option { } fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) { - if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) { + let expr_span = cx.tcx.hir().span(expr.hir_id); + if in_macro(expr_span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) { return; } @@ -1300,10 +1306,12 @@ fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[A // to prevent false positives as there is currently no better way to detect if code was excluded by // a macro. See PR #6435 if_chain! { - if let Some(match_snippet) = snippet_opt(cx, expr.span); + let expr_span = cx.tcx.hir().span(expr.hir_id); + if let Some(match_snippet) = snippet_opt(cx, expr_span); let arm_span = cx.tcx.hir().span(arms[0].hir_id); if let Some(arm_snippet) = snippet_opt(cx, arm_span); - if let Some(ex_snippet) = snippet_opt(cx, ex.span); + let ex_span = cx.tcx.hir().span(ex.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("=>"); then { @@ -1313,13 +1321,19 @@ fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[A } } - let matched_vars = ex.span; + let matched_vars = cx.tcx.hir().span(ex.hir_id); 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() { + let mut snippet_body = if cx.tcx.hir().span(match_body.hir_id).from_expansion() { Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string() } else { - snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string() + snippet_block( + cx, + cx.tcx.hir().span(match_body.hir_id), + "..", + Some(cx.tcx.hir().span(expr.hir_id)), + ) + .to_string() }; // Do we need to add ';' to suggestion ? @@ -1350,7 +1364,7 @@ fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[A "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)), + " ".repeat(indent_of(cx, cx.tcx.hir().span(expr.hir_id)).unwrap_or(0)), snippet_with_applicability( cx, cx.tcx.hir().span(parent_let_node.pat.hir_id), @@ -1362,7 +1376,7 @@ fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[A ) } else { // If we are in closure, we need curly braces around suggestion - let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0)); + let mut indent = " ".repeat(indent_of(cx, cx.tcx.hir().span(ex.hir_id)).unwrap_or(0)); let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string()); if let Some(parent_expr) = get_parent_expr(cx, expr) { if let ExprKind::Closure(..) = parent_expr.kind { @@ -1373,7 +1387,7 @@ fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[A } }; ( - expr.span, + cx.tcx.hir().span(expr.hir_id), format!( "{}let {} = {};\n{}{}{}", cbrace_start, @@ -1399,7 +1413,7 @@ fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[A span_lint_and_sugg( cx, MATCH_SINGLE_BINDING, - expr.span, + cx.tcx.hir().span(expr.hir_id), "this match could be replaced by its body itself", "consider using the match body instead", snippet_body, @@ -1710,11 +1724,11 @@ mod redundant_pattern_match { |diag| { // while let ... = ... { ... } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - let expr_span = expr.span; + let expr_span = cx.tcx.hir().span(expr.hir_id); // while let ... = ... { ... } // ^^^ - let op_span = result_expr.span.source_callsite(); + let op_span = cx.tcx.hir().span(result_expr.hir_id).source_callsite(); // while let ... = ... { ... } // ^^^^^^^^^^^^^^^^^^^ @@ -1796,7 +1810,7 @@ mod redundant_pattern_match { }; if let Some(good_method) = found_good_method { - let span = expr.span.to(op.span); + let span = cx.tcx.hir().span(expr.hir_id).to(cx.tcx.hir().span(op.hir_id)); let result_expr = match &op.kind { ExprKind::AddrOf(_, _, borrowed) => borrowed, _ => op, @@ -1804,13 +1818,17 @@ mod redundant_pattern_match { span_lint_and_then( cx, REDUNDANT_PATTERN_MATCHING, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("redundant pattern matching, consider using `{}`", good_method), |diag| { diag.span_suggestion( span, "try this", - format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method), + format!( + "{}.{}", + snippet(cx, cx.tcx.hir().span(result_expr.hir_id), "_"), + good_method + ), Applicability::MaybeIncorrect, // snippet ); }, @@ -1936,10 +1954,10 @@ fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) { span_lint_and_then( cx, MATCH_SAME_ARMS, - j.body.span, + cx.tcx.hir().span(j.body.hir_id), "this `match` has identical arm bodies", |diag| { - diag.span_note(i.body.span, "same as this"); + diag.span_note(cx.tcx.hir().span(i.body.hir_id), "same as this"); // Note: this does not use `span_suggestion` on purpose: // there is no clean way @@ -1956,7 +1974,7 @@ fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) { // note that i.pat cannot be _, because that would mean that we're // hiding all the subsequent arms, and rust won't compile diag.span_note( - i.body.span, + cx.tcx.hir().span(i.body.hir_id), &format!( "`{}` has the same arm body as the `_` wildcard, consider removing it", lhs diff --git a/src/tools/clippy/clippy_lints/src/mem_discriminant.rs b/src/tools/clippy/clippy_lints/src/mem_discriminant.rs index c71c2ee7d70af..c56eebac2a6de 100644 --- a/src/tools/clippy/clippy_lints/src/mem_discriminant.rs +++ b/src/tools/clippy/clippy_lints/src/mem_discriminant.rs @@ -45,7 +45,7 @@ impl<'tcx> LateLintPass<'tcx> for MemDiscriminant { span_lint_and_then( cx, MEM_DISCRIMINANT_NON_ENUM, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("calling `mem::discriminant` on non-enum type `{}`", ty_param), |diag| { // if this is a reference to an enum, suggest dereferencing @@ -67,9 +67,9 @@ impl<'tcx> LateLintPass<'tcx> for MemDiscriminant { let derefs: String = iter::repeat('*').take(derefs_needed).collect(); diag.span_suggestion( - param.span, + cx.tcx.hir().span(param.hir_id), "try dereferencing", - format!("{}{}", derefs, snippet(cx, cur_expr.span, "")), + format!("{}{}", derefs, snippet(cx, cx.tcx.hir().span(cur_expr.hir_id), "")), Applicability::MachineApplicable, ); } diff --git a/src/tools/clippy/clippy_lints/src/mem_forget.rs b/src/tools/clippy/clippy_lints/src/mem_forget.rs index d34f9761e26f9..978fd8f5bb4c3 100644 --- a/src/tools/clippy/clippy_lints/src/mem_forget.rs +++ b/src/tools/clippy/clippy_lints/src/mem_forget.rs @@ -34,7 +34,7 @@ impl<'tcx> LateLintPass<'tcx> for MemForget { let forgot_ty = cx.typeck_results().expr_ty(&args[0]); if forgot_ty.ty_adt_def().map_or(false, |def| def.has_dtor(cx.tcx)) { - span_lint(cx, MEM_FORGET, e.span, "usage of `mem::forget` on `Drop` type"); + span_lint(cx, MEM_FORGET, cx.tcx.hir().span(e.hir_id), "usage of `mem::forget` on `Drop` type"); } } } diff --git a/src/tools/clippy/clippy_lints/src/mem_replace.rs b/src/tools/clippy/clippy_lints/src/mem_replace.rs index 19087b0207714..56486b4c4d261 100644 --- a/src/tools/clippy/clippy_lints/src/mem_replace.rs +++ b/src/tools/clippy/clippy_lints/src/mem_replace.rs @@ -151,7 +151,7 @@ fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<' "consider using", format!( "std::ptr::read({})", - snippet_with_applicability(cx, dest.span, "", &mut applicability) + snippet_with_applicability(cx, cx.tcx.hir().span(dest.hir_id), "", &mut applicability) ), applicability, ); @@ -175,7 +175,7 @@ fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<' "consider using", format!( "std::ptr::read({})", - snippet_with_applicability(cx, dest.span, "", &mut applicability) + snippet_with_applicability(cx, cx.tcx.hir().span(dest.hir_id), "", &mut applicability) ), applicability, ); @@ -209,7 +209,7 @@ fn check_replace_with_default(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr< "replacing a value of type `T` with `T::default()` is better expressed using `std::mem::take`", |diag| { if !in_macro(expr_span) { - let suggestion = format!("std::mem::take({})", snippet(cx, dest.span, "")); + let suggestion = format!("std::mem::take({})", snippet(cx, cx.tcx.hir().span(dest.hir_id), "")); diag.span_suggestion( expr_span, @@ -248,10 +248,11 @@ impl<'tcx> LateLintPass<'tcx> for MemReplace { if match_def_path(cx, def_id, &paths::MEM_REPLACE); if let [dest, src] = &**func_args; then { - check_replace_option_with_none(cx, src, dest, expr.span); - check_replace_with_uninit(cx, src, dest, expr.span); + let expr_span = cx.tcx.hir().span(expr.hir_id); + check_replace_option_with_none(cx, src, dest, expr_span); + check_replace_with_uninit(cx, src, dest, expr_span); if meets_msrv(self.msrv.as_ref(), &MEM_REPLACE_WITH_DEFAULT_MSRV) { - check_replace_with_default(cx, src, dest, expr.span); + check_replace_with_default(cx, src, dest, expr_span); } } } diff --git a/src/tools/clippy/clippy_lints/src/methods/bind_instead_of_map.rs b/src/tools/clippy/clippy_lints/src/methods/bind_instead_of_map.rs index 5decb81d9f2e2..dca7655a37b34 100644 --- a/src/tools/clippy/clippy_lints/src/methods/bind_instead_of_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/bind_instead_of_map.rs @@ -96,19 +96,20 @@ pub(crate) trait BindInsteadOfMap { return false; } - let some_inner_snip = if inner_expr.span.from_expansion() { - snippet_with_macro_callsite(cx, inner_expr.span, "_") + let inner_expr_span = cx.tcx.hir().span(inner_expr.hir_id); + let some_inner_snip = if inner_expr_span.from_expansion() { + snippet_with_macro_callsite(cx, inner_expr_span, "_") } else { - snippet(cx, inner_expr.span, "_") + snippet(cx, inner_expr_span, "_") }; let closure_args_snip = snippet(cx, closure_args_span, ".."); - let option_snip = snippet(cx, args[0].span, ".."); + let option_snip = snippet(cx, cx.tcx.hir().span(args[0].hir_id), ".."); let note = format!("{}.{}({} {})", option_snip, Self::GOOD_METHOD_NAME, closure_args_snip, some_inner_snip); span_lint_and_sugg( cx, BIND_INSTEAD_OF_MAP, - expr.span, + cx.tcx.hir().span(expr.hir_id), Self::lint_msg().as_ref(), "try this", note, @@ -124,15 +125,16 @@ pub(crate) trait BindInsteadOfMap { fn lint_closure(cx: &LateContext<'_>, expr: &hir::Expr<'_>, closure_expr: &hir::Expr<'_>) -> bool { let mut suggs = Vec::new(); let can_sugg: bool = find_all_ret_expressions(cx, closure_expr, |ret_expr| { + let ret_expr_span = cx.tcx.hir().span(ret_expr.hir_id); if_chain! { - if !in_macro(ret_expr.span); + if !in_macro(ret_expr_span); if let hir::ExprKind::Call(ref func_path, ref args) = ret_expr.kind; if let hir::ExprKind::Path(ref qpath) = func_path.kind; if match_qpath(qpath, Self::BAD_VARIANT_QPATH); if args.len() == 1; if !contains_return(&args[0]); then { - suggs.push((ret_expr.span, args[0].span.source_callsite())); + suggs.push((ret_expr_span, cx.tcx.hir().span(args[0].hir_id).source_callsite())); true } else { false @@ -141,12 +143,12 @@ pub(crate) trait BindInsteadOfMap { }); if can_sugg { - span_lint_and_then(cx, BIND_INSTEAD_OF_MAP, expr.span, Self::lint_msg().as_ref(), |diag| { + span_lint_and_then(cx, BIND_INSTEAD_OF_MAP, cx.tcx.hir().span(expr.hir_id), Self::lint_msg().as_ref(), |diag| { multispan_sugg_with_applicability( diag, "try this", Applicability::MachineApplicable, - std::iter::once((*method_calls(expr, 1).2.get(0).unwrap(), Self::GOOD_METHOD_NAME.into())).chain( + std::iter::once((*method_calls(cx, expr, 1).2.get(0).unwrap(), Self::GOOD_METHOD_NAME.into())).chain( suggs .into_iter() .map(|(span1, span2)| (span1, snippet(cx, span2, "_").into())), @@ -179,10 +181,10 @@ pub(crate) trait BindInsteadOfMap { span_lint_and_sugg( cx, BIND_INSTEAD_OF_MAP, - expr.span, + cx.tcx.hir().span(expr.hir_id), Self::no_op_msg().as_ref(), "use the expression directly", - snippet(cx, args[0].span, "..").into(), + snippet(cx, cx.tcx.hir().span(args[0].hir_id), "..").into(), Applicability::MachineApplicable, ); true diff --git a/src/tools/clippy/clippy_lints/src/methods/bytes_nth.rs b/src/tools/clippy/clippy_lints/src/methods/bytes_nth.rs index 71a7e195e41ce..57a7ee6335b04 100644 --- a/src/tools/clippy/clippy_lints/src/methods/bytes_nth.rs +++ b/src/tools/clippy/clippy_lints/src/methods/bytes_nth.rs @@ -24,13 +24,13 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, iter_args: &' span_lint_and_sugg( cx, BYTES_NTH, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("called `.byte().nth()` on a `{}`", caller_type), "try", format!( "{}.as_bytes().get({})", - snippet_with_applicability(cx, iter_args[0].span, "..", &mut applicability), - snippet_with_applicability(cx, args[1].span, "..", &mut applicability) + snippet_with_applicability(cx, cx.tcx.hir().span(iter_args[0].hir_id), "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(args[1].hir_id), "..", &mut applicability) ), applicability, ); diff --git a/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs b/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs index 4a130ed47db15..4688744b74b14 100644 --- a/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs +++ b/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs @@ -16,7 +16,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr< span_lint_and_then( cx, CLONE_DOUBLE_REF, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!( "using `clone` on a double-reference; \ this will copy the reference of type `{}` instead of cloning the inner type", @@ -34,13 +34,13 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr< let derefs: String = iter::repeat('*').take(n).collect(); let explicit = format!("<{}{}>::clone({})", refs, ty, snip); diag.span_suggestion( - expr.span, + cx.tcx.hir().span(expr.hir_id), "try dereferencing it", format!("{}({}{}).clone()", refs, derefs, snip.deref()), Applicability::MaybeIncorrect, ); diag.span_suggestion( - expr.span, + cx.tcx.hir().span(expr.hir_id), "or try being explicit if you are sure, that you want to clone a reference", explicit, Applicability::MaybeIncorrect, @@ -97,11 +97,16 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr< span_lint_and_then( cx, CLONE_ON_COPY, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("using `clone` on type `{}` which implements the `Copy` trait", ty), |diag| { if let Some((text, snip)) = snip { - diag.span_suggestion(expr.span, text, snip, Applicability::MachineApplicable); + diag.span_suggestion( + cx.tcx.hir().span(expr.hir_id), + text, + snip, + Applicability::MachineApplicable, + ); } }, ); diff --git a/src/tools/clippy/clippy_lints/src/methods/clone_on_ref_ptr.rs b/src/tools/clippy/clippy_lints/src/methods/clone_on_ref_ptr.rs index 3d5a68d69d7d2..6d145c7eeeae1 100644 --- a/src/tools/clippy/clippy_lints/src/methods/clone_on_ref_ptr.rs +++ b/src/tools/clippy/clippy_lints/src/methods/clone_on_ref_ptr.rs @@ -21,12 +21,12 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr< return; }; - let snippet = snippet_with_macro_callsite(cx, arg.span, ".."); + let snippet = snippet_with_macro_callsite(cx, cx.tcx.hir().span(arg.hir_id), ".."); span_lint_and_sugg( cx, CLONE_ON_REF_PTR, - expr.span, + cx.tcx.hir().span(expr.hir_id), "using `.clone()` on a ref-counted pointer", "try this", format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet), diff --git a/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs b/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs index 6866e9c652ab3..8397a7bc5d109 100644 --- a/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs +++ b/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs @@ -104,7 +104,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, method_span: Spa then { format_arg_expr_tup .iter() - .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned()) + .map(|a| snippet_with_applicability(cx, cx.tcx.hir().span(a.hir_id), "..", applicability).into_owned()) .collect() } else { unreachable!() @@ -142,7 +142,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, method_span: Spa let arg_root = get_arg_root(cx, &args[1]); - let span_replace_word = method_span.with_hi(expr.span.hi()); + let span_replace_word = method_span.with_hi(cx.tcx.hir().span(expr.hir_id).hi()); let mut applicability = Applicability::MachineApplicable; @@ -153,13 +153,13 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, method_span: Spa if let hir::StmtKind::Local(local) = &block.stmts[0].kind; if let Some(arg_root) = &local.init; if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind; - if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1; + if is_expn_of(cx.tcx.hir().span(inner_fun.hir_id), "format").is_some() && inner_args.len() == 1; if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind; then { let fmt_spec = &format_args[0]; let fmt_args = &format_args[1]; - let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()]; + let mut args = vec![snippet(cx, cx.tcx.hir().span(fmt_spec.hir_id), "..").into_owned()]; args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability)); @@ -179,7 +179,8 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, method_span: Spa } } - let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability); + let mut arg_root_snippet: Cow<'_, _> = + snippet_with_applicability(cx, cx.tcx.hir().span(arg_root.hir_id), "..", &mut applicability); if requires_to_string(cx, arg_root) { arg_root_snippet.to_mut().push_str(".to_string()"); } diff --git a/src/tools/clippy/clippy_lints/src/methods/expect_used.rs b/src/tools/clippy/clippy_lints/src/methods/expect_used.rs index 90b781bd9d190..b1f8019ee378f 100644 --- a/src/tools/clippy/clippy_lints/src/methods/expect_used.rs +++ b/src/tools/clippy/clippy_lints/src/methods/expect_used.rs @@ -21,7 +21,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, expect_args: &[h span_lint_and_help( cx, lint, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("used `expect()` on `{}` value", kind,), None, &format!("if this value is an `{}`, it will panic", none_value,), diff --git a/src/tools/clippy/clippy_lints/src/methods/filetype_is_file.rs b/src/tools/clippy/clippy_lints/src/methods/filetype_is_file.rs index b03835f97e634..141731f2877e7 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filetype_is_file.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filetype_is_file.rs @@ -25,12 +25,12 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Exp lint_unary = "!"; verb = "denies"; help_unary = ""; - span = parent.span; + span = cx.tcx.hir().span(parent.hir_id); } else { lint_unary = ""; verb = "covers"; help_unary = "!"; - span = expr.span; + span = cx.tcx.hir().span(expr.hir_id); } } let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb); diff --git a/src/tools/clippy/clippy_lints/src/methods/filter_flat_map.rs b/src/tools/clippy/clippy_lints/src/methods/filter_flat_map.rs index 8da867fce515c..079aac1855cb0 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filter_flat_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filter_flat_map.rs @@ -16,6 +16,6 @@ pub(super) fn check<'tcx>( let msg = "called `filter(..).flat_map(..)` on an `Iterator`"; let hint = "this is more succinctly expressed by calling `.flat_map(..)` \ and filtering by returning `iter::empty()`"; - span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint); + span_lint_and_help(cx, FILTER_MAP, cx.tcx.hir().span(expr.hir_id), msg, None, hint); } } diff --git a/src/tools/clippy/clippy_lints/src/methods/filter_map.rs b/src/tools/clippy/clippy_lints/src/methods/filter_map.rs index f559160004cb1..7cad31155cac8 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filter_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filter_map.rs @@ -78,7 +78,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, is_ let msg = format!("`{}(..).map(..)` can be simplified as `{0}_map(..)`", filter_name); let to_opt = if is_result { ".ok()" } else { "" }; let sugg = format!("{}_map(|{}| {}{})", filter_name, map_param_ident, - snippet(cx, map_arg.span, ".."), to_opt); + snippet(cx, cx.tcx.hir().span(map_arg.hir_id), ".."), to_opt); span_lint_and_sugg(cx, lint, span, &msg, "try", sugg, Applicability::MachineApplicable); } } diff --git a/src/tools/clippy/clippy_lints/src/methods/filter_map_flat_map.rs b/src/tools/clippy/clippy_lints/src/methods/filter_map_flat_map.rs index a6db138623a8c..71e75a64130cb 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filter_map_flat_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filter_map_flat_map.rs @@ -16,6 +16,6 @@ pub(super) fn check<'tcx>( let msg = "called `filter_map(..).flat_map(..)` on an `Iterator`"; let hint = "this is more succinctly expressed by calling `.flat_map(..)` \ and filtering by returning `iter::empty()`"; - span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint); + span_lint_and_help(cx, FILTER_MAP, cx.tcx.hir().span(expr.hir_id), msg, None, hint); } } diff --git a/src/tools/clippy/clippy_lints/src/methods/filter_map_identity.rs b/src/tools/clippy/clippy_lints/src/methods/filter_map_identity.rs index 9e646360a40c3..b23c1efffb097 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filter_map_identity.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filter_map_identity.rs @@ -20,7 +20,7 @@ pub(super) fn check( span_lint_and_sugg( cx, FILTER_MAP_IDENTITY, - filter_map_span.with_hi(expr.span.hi()), + filter_map_span.with_hi(cx.tcx.hir().span(expr.hir_id).hi()), message, "try", "flatten()".to_string(), diff --git a/src/tools/clippy/clippy_lints/src/methods/filter_map_map.rs b/src/tools/clippy/clippy_lints/src/methods/filter_map_map.rs index d015b4c7b385e..ed41277d4131f 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filter_map_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filter_map_map.rs @@ -15,6 +15,6 @@ pub(super) fn check<'tcx>( if match_trait_method(cx, expr, &paths::ITERATOR) { let msg = "called `filter_map(..).map(..)` on an `Iterator`"; let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead"; - span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint); + span_lint_and_help(cx, FILTER_MAP, cx.tcx.hir().span(expr.hir_id), msg, None, hint); } } diff --git a/src/tools/clippy/clippy_lints/src/methods/filter_map_next.rs b/src/tools/clippy/clippy_lints/src/methods/filter_map_next.rs index a789df922ffdb..242aa7bc54954 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filter_map_next.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filter_map_next.rs @@ -21,20 +21,20 @@ pub(super) fn check<'tcx>( let msg = "called `filter_map(..).next()` on an `Iterator`. This is more succinctly expressed by calling \ `.find_map(..)` instead"; - let filter_snippet = snippet(cx, filter_args[1].span, ".."); + let filter_snippet = snippet(cx, cx.tcx.hir().span(filter_args[1].hir_id), ".."); if filter_snippet.lines().count() <= 1 { - let iter_snippet = snippet(cx, filter_args[0].span, ".."); + let iter_snippet = snippet(cx, cx.tcx.hir().span(filter_args[0].hir_id), ".."); span_lint_and_sugg( cx, FILTER_MAP_NEXT, - expr.span, + cx.tcx.hir().span(expr.hir_id), msg, "try this", format!("{}.find_map({})", iter_snippet, filter_snippet), Applicability::MachineApplicable, ); } else { - span_lint(cx, FILTER_MAP_NEXT, expr.span, msg); + span_lint(cx, FILTER_MAP_NEXT, cx.tcx.hir().span(expr.hir_id), msg); } } } diff --git a/src/tools/clippy/clippy_lints/src/methods/filter_next.rs b/src/tools/clippy/clippy_lints/src/methods/filter_next.rs index 81619e73017f2..5df6fe0add2ed 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filter_next.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filter_next.rs @@ -11,21 +11,21 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, fil if match_trait_method(cx, expr, &paths::ITERATOR) { let msg = "called `filter(..).next()` on an `Iterator`. This is more succinctly expressed by calling \ `.find(..)` instead"; - let filter_snippet = snippet(cx, filter_args[1].span, ".."); + let filter_snippet = snippet(cx, cx.tcx.hir().span(filter_args[1].hir_id), ".."); if filter_snippet.lines().count() <= 1 { - let iter_snippet = snippet(cx, filter_args[0].span, ".."); + let iter_snippet = snippet(cx, cx.tcx.hir().span(filter_args[0].hir_id), ".."); // add note if not multi-line span_lint_and_sugg( cx, FILTER_NEXT, - expr.span, + cx.tcx.hir().span(expr.hir_id), msg, "try this", format!("{}.find({})", iter_snippet, filter_snippet), Applicability::MachineApplicable, ); } else { - span_lint(cx, FILTER_NEXT, expr.span, msg); + span_lint(cx, FILTER_NEXT, cx.tcx.hir().span(expr.hir_id), msg); } } } diff --git a/src/tools/clippy/clippy_lints/src/methods/flat_map_identity.rs b/src/tools/clippy/clippy_lints/src/methods/flat_map_identity.rs index ce3194f8a2373..bf5400ef087a7 100644 --- a/src/tools/clippy/clippy_lints/src/methods/flat_map_identity.rs +++ b/src/tools/clippy/clippy_lints/src/methods/flat_map_identity.rs @@ -21,7 +21,7 @@ pub(super) fn check<'tcx>( span_lint_and_sugg( cx, FLAT_MAP_IDENTITY, - flat_map_span.with_hi(expr.span.hi()), + flat_map_span.with_hi(cx.tcx.hir().span(expr.hir_id).hi()), message, "try", "flatten()".to_string(), diff --git a/src/tools/clippy/clippy_lints/src/methods/from_iter_instead_of_collect.rs b/src/tools/clippy/clippy_lints/src/methods/from_iter_instead_of_collect.rs index e50d0a3340026..f6ab7cf80f88c 100644 --- a/src/tools/clippy/clippy_lints/src/methods/from_iter_instead_of_collect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/from_iter_instead_of_collect.rs @@ -24,7 +24,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Exp span_lint_and_sugg( cx, FROM_ITER_INSTEAD_OF_COLLECT, - expr.span, + cx.tcx.hir().span(expr.hir_id), "usage of `FromIterator::from_iter`", "use `.collect()` instead of `::from_iter()`", sugg, @@ -36,7 +36,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Exp fn extract_turbofish(cx: &LateContext<'_>, expr: &hir::Expr<'_>, ty: Ty<'tcx>) -> String { if_chain! { - let call_site = expr.span.source_callsite(); + let call_site = cx.tcx.hir().span(expr.hir_id).source_callsite(); if let Ok(snippet) = cx.sess().source_map().span_to_snippet(call_site); let snippet_split = snippet.split("::").collect::>(); if let Some((_, elements)) = snippet_split.split_last(); diff --git a/src/tools/clippy/clippy_lints/src/methods/get_unwrap.rs b/src/tools/clippy/clippy_lints/src/methods/get_unwrap.rs index e157db2712a9a..d765cd02d7b41 100644 --- a/src/tools/clippy/clippy_lints/src/methods/get_unwrap.rs +++ b/src/tools/clippy/clippy_lints/src/methods/get_unwrap.rs @@ -16,7 +16,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, get_args let mut applicability = Applicability::MachineApplicable; let expr_ty = cx.typeck_results().expr_ty(&get_args[0]); let get_args_str = if get_args.len() > 1 { - snippet_with_applicability(cx, get_args[1].span, "..", &mut applicability) + snippet_with_applicability(cx, cx.tcx.hir().span(get_args[1].hir_id), "..", &mut applicability) } else { return; // not linting on a .get().unwrap() chain or variant }; @@ -40,7 +40,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, get_args return; // caller is not a type that we want to lint }; - let mut span = expr.span; + let mut span = cx.tcx.hir().span(expr.hir_id); // Handle the case where the result is immediately dereferenced // by not requiring ref and pulling the dereference into the @@ -51,7 +51,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, get_args if let hir::ExprKind::Unary(hir::UnOp::Deref, _) = parent.kind; then { needs_ref = false; - span = parent.span; + span = cx.tcx.hir().span(parent.hir_id); } } @@ -76,7 +76,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, get_args format!( "{}{}[{}]", borrow_str, - snippet_with_applicability(cx, get_args[0].span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(get_args[0].hir_id), "..", &mut applicability), get_args_str ), applicability, diff --git a/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs b/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs index 3045b09c2389f..7a956c2f585e2 100644 --- a/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs +++ b/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs @@ -23,7 +23,7 @@ pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, arg: &hir::Expr span_lint_and_then( cx, INEFFICIENT_TO_STRING, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("calling `to_string` on `{}`", arg_ty), |diag| { diag.help(&format!( @@ -31,9 +31,9 @@ pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, arg: &hir::Expr self_ty, deref_self_ty )); let mut applicability = Applicability::MachineApplicable; - let arg_snippet = snippet_with_applicability(cx, arg.span, "..", &mut applicability); + let arg_snippet = snippet_with_applicability(cx, cx.tcx.hir().span(arg.hir_id), "..", &mut applicability); diag.span_suggestion( - expr.span, + cx.tcx.hir().span(expr.hir_id), "try dereferencing the receiver", format!("({}{}).to_string()", "*".repeat(deref_count), arg_snippet), applicability, diff --git a/src/tools/clippy/clippy_lints/src/methods/inspect_for_each.rs b/src/tools/clippy/clippy_lints/src/methods/inspect_for_each.rs index 959457a5bfc96..9e945f5989fd4 100644 --- a/src/tools/clippy/clippy_lints/src/methods/inspect_for_each.rs +++ b/src/tools/clippy/clippy_lints/src/methods/inspect_for_each.rs @@ -14,7 +14,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, ins span_lint_and_help( cx, INSPECT_FOR_EACH, - inspect_span.with_hi(expr.span.hi()), + inspect_span.with_hi(cx.tcx.hir().span(expr.hir_id).hi()), msg, None, hint, diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_cloned_collect.rs b/src/tools/clippy/clippy_lints/src/methods/iter_cloned_collect.rs index c3e48ffa5fae4..00e986715d16f 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_cloned_collect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_cloned_collect.rs @@ -12,7 +12,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, iter_arg if_chain! { if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::vec_type); if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0])); - if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite()); + if let Some(to_replace) = cx.tcx.hir().span(expr.hir_id).trim_start(cx.tcx.hir().span(slice.hir_id).source_callsite()); then { span_lint_and_sugg( diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_count.rs b/src/tools/clippy/clippy_lints/src/methods/iter_count.rs index 869440e0165b2..e999b851fe06e 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_count.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_count.rs @@ -35,12 +35,12 @@ pub(crate) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, iter_args: &' span_lint_and_sugg( cx, ITER_COUNT, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("called `.{}().count()` on a `{}`", iter_method, caller_type), "try", format!( "{}.len()", - snippet_with_applicability(cx, iter_args[0].span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(iter_args[0].hir_id), "..", &mut applicability), ), applicability, ); diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_next_slice.rs b/src/tools/clippy/clippy_lints/src/methods/iter_next_slice.rs index c027ee8154962..358587888c42a 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_next_slice.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_next_slice.rs @@ -36,10 +36,10 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, ite span_lint_and_sugg( cx, ITER_NEXT_SLICE, - expr.span, + cx.tcx.hir().span(expr.hir_id), "using `.iter().next()` on a Slice without end index", "try calling", - format!("{}.get({})", snippet_with_applicability(cx, caller_var.span, "..", &mut applicability), start_idx), + format!("{}.get({})", snippet_with_applicability(cx, cx.tcx.hir().span(caller_var.hir_id), "..", &mut applicability), start_idx), applicability, ); } @@ -55,12 +55,12 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, ite span_lint_and_sugg( cx, ITER_NEXT_SLICE, - expr.span, + cx.tcx.hir().span(expr.hir_id), "using `.iter().next()` on an array", "try calling", format!( "{}.get(0)", - snippet_with_applicability(cx, caller_expr.span, "..", &mut applicability) + snippet_with_applicability(cx, cx.tcx.hir().span(caller_expr.hir_id), "..", &mut applicability) ), applicability, ); diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_nth.rs b/src/tools/clippy/clippy_lints/src/methods/iter_nth.rs index cc3e56ea87277..d8ec4972678c8 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_nth.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_nth.rs @@ -30,7 +30,7 @@ pub(super) fn check<'tcx>( span_lint_and_help( cx, ITER_NTH, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type), None, &format!("calling `.get{}()` is both faster and more readable", mut_str), diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_nth_zero.rs b/src/tools/clippy/clippy_lints/src/methods/iter_nth_zero.rs index 247192d81f3ec..878e0deb1b12d 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_nth_zero.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_nth_zero.rs @@ -16,10 +16,10 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, nth_args span_lint_and_sugg( cx, ITER_NTH_ZERO, - expr.span, + cx.tcx.hir().span(expr.hir_id), "called `.nth(0)` on a `std::iter::Iterator`, when `.next()` is equivalent", "try calling `.next()` instead of `.nth(0)`", - format!("{}.next()", snippet_with_applicability(cx, nth_args[0].span, "..", &mut applicability)), + format!("{}.next()", snippet_with_applicability(cx, cx.tcx.hir().span(nth_args[0].hir_id), "..", &mut applicability)), applicability, ); } diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_skip_next.rs b/src/tools/clippy/clippy_lints/src/methods/iter_skip_next.rs index 5f5969134e490..72cb01739a2ae 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_skip_next.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_skip_next.rs @@ -9,11 +9,15 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, skip_args: &[hir // lint if caller of skip is an Iterator if match_trait_method(cx, expr, &paths::ITERATOR) { if let [caller, n] = skip_args { - let hint = format!(".nth({})", snippet(cx, n.span, "..")); + let hint = format!(".nth({})", snippet(cx, cx.tcx.hir().span(n.hir_id), "..")); span_lint_and_sugg( cx, ITER_SKIP_NEXT, - expr.span.trim_start(caller.span).unwrap(), + cx.tcx + .hir() + .span(expr.hir_id) + .trim_start(cx.tcx.hir().span(caller.hir_id)) + .unwrap(), "called `skip(..).next()` on an iterator", "use `nth` instead", hint, diff --git a/src/tools/clippy/clippy_lints/src/methods/iterator_step_by_zero.rs b/src/tools/clippy/clippy_lints/src/methods/iterator_step_by_zero.rs index 3e05d7f76b75a..0deb9c93721db 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iterator_step_by_zero.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iterator_step_by_zero.rs @@ -11,7 +11,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, args: &' span_lint( cx, ITERATOR_STEP_BY_ZERO, - expr.span, + cx.tcx.hir().span(expr.hir_id), "`Iterator::step_by(0)` will panic at runtime", ); } diff --git a/src/tools/clippy/clippy_lints/src/methods/manual_saturating_arithmetic.rs b/src/tools/clippy/clippy_lints/src/methods/manual_saturating_arithmetic.rs index 0b414e0eb9567..f46a08bc1548e 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_saturating_arithmetic.rs +++ b/src/tools/clippy/clippy_lints/src/methods/manual_saturating_arithmetic.rs @@ -44,14 +44,14 @@ pub fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[&[hir::Expr<'_> span_lint_and_sugg( cx, super::MANUAL_SATURATING_ARITHMETIC, - expr.span, + cx.tcx.hir().span(expr.hir_id), "manual saturating arithmetic", &format!("try using `saturating_{}`", arith), format!( "{}.saturating_{}({})", - snippet_with_applicability(cx, arith_lhs.span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(arith_lhs.hir_id), "..", &mut applicability), arith, - snippet_with_applicability(cx, arith_rhs.span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(arith_rhs.hir_id), "..", &mut applicability), ), applicability, ); @@ -65,14 +65,14 @@ pub fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[&[hir::Expr<'_> span_lint_and_sugg( cx, super::MANUAL_SATURATING_ARITHMETIC, - expr.span, + cx.tcx.hir().span(expr.hir_id), "manual saturating arithmetic", &format!("try using `saturating_{}`", arith), format!( "{}.saturating_{}({})", - snippet_with_applicability(cx, arith_lhs.span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(arith_lhs.hir_id), "..", &mut applicability), arith, - snippet_with_applicability(cx, arith_rhs.span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(arith_rhs.hir_id), "..", &mut applicability), ), applicability, ); diff --git a/src/tools/clippy/clippy_lints/src/methods/map_collect_result_unit.rs b/src/tools/clippy/clippy_lints/src/methods/map_collect_result_unit.rs index 5b20e268d9f7e..d5155d67ec428 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_collect_result_unit.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_collect_result_unit.rs @@ -30,13 +30,13 @@ pub(super) fn check( span_lint_and_sugg( cx, MAP_COLLECT_RESULT_UNIT, - expr.span, + cx.tcx.hir().span(expr.hir_id), "`.map().collect()` can be replaced with `.try_for_each()`", "try this", format!( "{}.try_for_each({})", - snippet(cx, iter.span, ".."), - snippet(cx, map_fn.span, "..") + snippet(cx, cx.tcx.hir().span(iter.hir_id), ".."), + snippet(cx, cx.tcx.hir().span(map_fn.hir_id), "..") ), Applicability::MachineApplicable, ); diff --git a/src/tools/clippy/clippy_lints/src/methods/map_flatten.rs b/src/tools/clippy/clippy_lints/src/methods/map_flatten.rs index 14a14e4f9ecd1..749fc69fc151e 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_flatten.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_flatten.rs @@ -31,12 +31,15 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map // `(...).map(...)` has type `impl Iterator> "flat_map" }; - let func_snippet = snippet(cx, map_args[1].span, ".."); + let func_snippet = snippet(cx, cx.tcx.hir().span(map_args[1].hir_id), ".."); let hint = format!(".{0}({1})", method_to_use, func_snippet); span_lint_and_sugg( cx, MAP_FLATTEN, - expr.span.with_lo(map_args[0].span.hi()), + cx.tcx + .hir() + .span(expr.hir_id) + .with_lo(cx.tcx.hir().span(map_args[0].hir_id).hi()), "called `map(..).flatten()` on an `Iterator`", &format!("try using `{}` instead", method_to_use), hint, @@ -46,12 +49,15 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map // lint if caller of `.map().flatten()` is an Option if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym::option_type) { - let func_snippet = snippet(cx, map_args[1].span, ".."); + let func_snippet = snippet(cx, cx.tcx.hir().span(map_args[1].hir_id), ".."); let hint = format!(".and_then({})", func_snippet); span_lint_and_sugg( cx, MAP_FLATTEN, - expr.span.with_lo(map_args[0].span.hi()), + cx.tcx + .hir() + .span(expr.hir_id) + .with_lo(cx.tcx.hir().span(map_args[0].hir_id).hi()), "called `map(..).flatten()` on an `Option`", "try using `and_then` instead", hint, diff --git a/src/tools/clippy/clippy_lints/src/methods/map_unwrap_or.rs b/src/tools/clippy/clippy_lints/src/methods/map_unwrap_or.rs index 63b2cf87f32ad..85d79132cbe80 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_unwrap_or.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_unwrap_or.rs @@ -48,18 +48,18 @@ pub(super) fn check<'tcx>( `.map_or_else(, )` instead" }; // get snippets for args to map() and unwrap_or_else() - let map_snippet = snippet(cx, map_args[1].span, ".."); - let unwrap_snippet = snippet(cx, unwrap_args[1].span, ".."); + let map_snippet = snippet(cx, cx.tcx.hir().span(map_args[1].hir_id), ".."); + let unwrap_snippet = snippet(cx, cx.tcx.hir().span(unwrap_args[1].hir_id), ".."); // lint, with note if neither arg is > 1 line and both map() and // unwrap_or_else() have the same span let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1; - let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt(); + let same_span = cx.tcx.hir().span(map_args[1].hir_id).ctxt() == cx.tcx.hir().span(unwrap_args[1].hir_id).ctxt(); if same_span && !multiline { - let var_snippet = snippet(cx, map_args[0].span, ".."); + let var_snippet = snippet(cx, cx.tcx.hir().span(map_args[0].hir_id), ".."); span_lint_and_sugg( cx, MAP_UNWRAP_OR, - expr.span, + cx.tcx.hir().span(expr.hir_id), msg, "try this", format!("{}.map_or_else({}, {})", var_snippet, unwrap_snippet, map_snippet), @@ -67,7 +67,7 @@ pub(super) fn check<'tcx>( ); return true; } else if same_span && multiline { - span_lint(cx, MAP_UNWRAP_OR, expr.span, msg); + span_lint(cx, MAP_UNWRAP_OR, cx.tcx.hir().span(expr.hir_id), msg); return true; } } diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index a24972d772313..b9f2b9e0da901 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -1670,11 +1670,11 @@ impl_lint_pass!(Methods => [ impl<'tcx> LateLintPass<'tcx> for Methods { #[allow(clippy::too_many_lines)] fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { - if in_macro(expr.span) { + if in_macro(cx.tcx.hir().span(expr.hir_id)) { return; } - let (method_names, arg_lists, method_spans) = method_calls(expr, 2); + let (method_names, arg_lists, method_spans) = method_calls(cx, expr, 2); let method_names: Vec = method_names.iter().map(|s| s.as_str()).collect(); let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect(); @@ -2049,7 +2049,7 @@ fn lint_chars_cmp( suggest: &str, ) -> bool { if_chain! { - if let Some(args) = method_chain_args(info.chain, chain_methods); + if let Some(args) = method_chain_args(cx, info.chain, chain_methods); if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind; if arg_char.len() == 1; if let hir::ExprKind::Path(ref qpath) = fun.kind; @@ -2066,14 +2066,14 @@ fn lint_chars_cmp( span_lint_and_sugg( cx, lint, - info.expr.span, + cx.tcx.hir().span(info.expr.hir_id), &format!("you should use the `{}` method", suggest), "like this", format!("{}{}.{}({})", if info.eq { "" } else { "!" }, - snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(args[0][0].hir_id), "..", &mut applicability), suggest, - snippet_with_applicability(cx, arg_char[0].span, "..", &mut applicability)), + snippet_with_applicability(cx, cx.tcx.hir().span(arg_char[0].hir_id), "..", &mut applicability)), applicability, ); @@ -2107,7 +2107,7 @@ fn lint_chars_cmp_with_unwrap<'tcx>( suggest: &str, ) -> bool { if_chain! { - if let Some(args) = method_chain_args(info.chain, chain_methods); + if let Some(args) = method_chain_args(cx, info.chain, chain_methods); if let hir::ExprKind::Lit(ref lit) = info.other.kind; if let ast::LitKind::Char(c) = lit.node; then { @@ -2115,12 +2115,12 @@ fn lint_chars_cmp_with_unwrap<'tcx>( span_lint_and_sugg( cx, lint, - info.expr.span, + cx.tcx.hir().span(info.expr.hir_id), &format!("you should use the `{}` method", suggest), "like this", format!("{}{}.{}('{}')", if info.eq { "" } else { "!" }, - snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(args[0][0].hir_id), "..", &mut applicability), suggest, c), applicability, @@ -2158,7 +2158,7 @@ fn get_hint_if_single_char_arg( let string = r.as_str(); if string.chars().count() == 1; then { - let snip = snippet_with_applicability(cx, arg.span, &string, applicability); + let snip = snippet_with_applicability(cx, cx.tcx.hir().span(arg.hir_id), "..", applicability); let ch = if let ast::StrStyle::Raw(nhash) = style { let nhash = nhash as usize; // for raw string: r##"a"## diff --git a/src/tools/clippy/clippy_lints/src/methods/ok_expect.rs b/src/tools/clippy/clippy_lints/src/methods/ok_expect.rs index c1706cc7cc7d2..6342be8a845a8 100644 --- a/src/tools/clippy/clippy_lints/src/methods/ok_expect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/ok_expect.rs @@ -20,7 +20,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, ok_args: &[hir:: span_lint_and_help( cx, OK_EXPECT, - expr.span, + cx.tcx.hir().span(expr.hir_id), "called `ok().expect()` on a `Result` value", None, "you can call `expect()` directly on the `Result`", diff --git a/src/tools/clippy/clippy_lints/src/methods/option_as_ref_deref.rs b/src/tools/clippy/clippy_lints/src/methods/option_as_ref_deref.rs index 89067dbfe0e51..884fbd5c84137 100644 --- a/src/tools/clippy/clippy_lints/src/methods/option_as_ref_deref.rs +++ b/src/tools/clippy/clippy_lints/src/methods/option_as_ref_deref.rs @@ -96,12 +96,22 @@ pub(super) fn check<'tcx>( if is_deref { let current_method = if is_mut { - format!(".as_mut().map({})", snippet(cx, map_args[1].span, "..")) + format!( + ".as_mut().map({})", + snippet(cx, cx.tcx.hir().span(map_args[1].hir_id), "..") + ) } else { - format!(".as_ref().map({})", snippet(cx, map_args[1].span, "..")) + format!( + ".as_ref().map({})", + snippet(cx, cx.tcx.hir().span(map_args[1].hir_id), "..") + ) }; let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" }; - let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint); + let hint = format!( + "{}.{}()", + snippet(cx, cx.tcx.hir().span(as_ref_args[0].hir_id), ".."), + method_hint + ); let suggestion = format!("try using {} instead", method_hint); let msg = format!( @@ -112,7 +122,7 @@ pub(super) fn check<'tcx>( span_lint_and_sugg( cx, OPTION_AS_REF_DEREF, - expr.span, + cx.tcx.hir().span(expr.hir_id), &msg, &suggestion, hint, diff --git a/src/tools/clippy/clippy_lints/src/methods/option_map_or_none.rs b/src/tools/clippy/clippy_lints/src/methods/option_map_or_none.rs index 64f6ebc5062ef..ab00e5ea16be0 100644 --- a/src/tools/clippy/clippy_lints/src/methods/option_map_or_none.rs +++ b/src/tools/clippy/clippy_lints/src/methods/option_map_or_none.rs @@ -40,8 +40,8 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map }; if is_option { - let self_snippet = snippet(cx, map_or_args[0].span, ".."); - let func_snippet = snippet(cx, map_or_args[2].span, ".."); + let self_snippet = snippet(cx, cx.tcx.hir().span(map_or_args[0].hir_id), ".."); + let func_snippet = snippet(cx, cx.tcx.hir().span(map_or_args[2].hir_id), ".."); let msg = "called `map_or(None, ..)` on an `Option` value. This can be done more directly by calling \ `and_then(..)` instead"; ( @@ -53,7 +53,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map } else if f_arg_is_some { let msg = "called `map_or(None, Some)` on a `Result` value. This can be done more directly by calling \ `ok()` instead"; - let self_snippet = snippet(cx, map_or_args[0].span, ".."); + let self_snippet = snippet(cx, cx.tcx.hir().span(map_or_args[0].hir_id), ".."); ( RESULT_MAP_OR_INTO_OPTION, msg, @@ -69,7 +69,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map span_lint_and_sugg( cx, lint_name, - expr.span, + cx.tcx.hir().span(expr.hir_id), msg, instead, hint, diff --git a/src/tools/clippy/clippy_lints/src/methods/option_map_unwrap_or.rs b/src/tools/clippy/clippy_lints/src/methods/option_map_unwrap_or.rs index 7cdd49bbf0307..91d138cb82882 100644 --- a/src/tools/clippy/clippy_lints/src/methods/option_map_unwrap_or.rs +++ b/src/tools/clippy/clippy_lints/src/methods/option_map_unwrap_or.rs @@ -43,13 +43,13 @@ pub(super) fn check<'tcx>( } } - if differing_macro_contexts(unwrap_args[1].span, map_span) { + if differing_macro_contexts(cx.tcx.hir().span(unwrap_args[1].hir_id), map_span) { return; } let mut applicability = Applicability::MachineApplicable; // get snippet for unwrap_or() - let unwrap_snippet = snippet_with_applicability(cx, unwrap_args[1].span, "..", &mut applicability); + let unwrap_snippet = snippet_with_applicability(cx, cx.tcx.hir().span(unwrap_args[1].hir_id), "..", &mut applicability); // lint message // comparing the snippet from source to raw text ("None") below is safe // because we already have checked the type. @@ -66,15 +66,15 @@ pub(super) fn check<'tcx>( arg, suggest ); - span_lint_and_then(cx, MAP_UNWRAP_OR, expr.span, msg, |diag| { - let map_arg_span = map_args[1].span; + span_lint_and_then(cx, MAP_UNWRAP_OR, cx.tcx.hir().span(expr.hir_id), msg, |diag| { + let map_arg_span = cx.tcx.hir().span(map_args[1].hir_id); let mut suggestion = vec![ ( map_span, String::from(if unwrap_snippet_none { "and_then" } else { "map_or" }), ), - (expr.span.with_lo(unwrap_args[0].span.hi()), String::from("")), + (cx.tcx.hir().span(expr.hir_id).with_lo(cx.tcx.hir().span(unwrap_args[0].hir_id).hi()), String::from("")), ]; if !unwrap_snippet_none { diff --git a/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs b/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs index 5f7fc431d2248..b6dc12fac0193 100644 --- a/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs +++ b/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs @@ -53,7 +53,7 @@ pub(super) fn check<'tcx>( "try this", format!( "{}.unwrap_or_default()", - snippet_with_applicability(cx, self_expr.span, "..", &mut applicability) + snippet_with_applicability(cx, cx.tcx.hir().span(self_expr.hir_id), "..", &mut applicability) ), applicability, ); @@ -118,7 +118,7 @@ pub(super) fn check<'tcx>( let sugg: Cow<'_, str> = { let (snippet_span, use_lambda) = match (fn_has_arguments, fun_span) { (false, Some(fun_span)) => (fun_span, false), - _ => (arg.span, true), + _ => (cx.tcx.hir().span(arg.hir_id), true), }; let snippet = { let not_macro_argument_snippet = snippet_with_macro_callsite(cx, snippet_span, ".."); @@ -159,13 +159,41 @@ pub(super) fn check<'tcx>( match args[1].kind { hir::ExprKind::Call(ref fun, ref or_args) => { let or_has_args = !or_args.is_empty(); - if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) { - let fun_span = if or_has_args { None } else { Some(fun.span) }; - check_general_case(cx, name, method_span, &args[0], &args[1], expr.span, fun_span); + if !check_unwrap_or_default( + cx, + name, + fun, + &args[0], + &args[1], + or_has_args, + cx.tcx.hir().span(expr.hir_id), + ) { + let fun_span = if or_has_args { + None + } else { + Some(cx.tcx.hir().span(fun.hir_id)) + }; + check_general_case( + cx, + name, + method_span, + &args[0], + &args[1], + cx.tcx.hir().span(expr.hir_id), + fun_span, + ); } }, hir::ExprKind::Index(..) | hir::ExprKind::MethodCall(..) => { - check_general_case(cx, name, method_span, &args[0], &args[1], expr.span, None); + check_general_case( + cx, + name, + method_span, + &args[0], + &args[1], + cx.tcx.hir().span(expr.hir_id), + None, + ); }, _ => {}, } diff --git a/src/tools/clippy/clippy_lints/src/methods/search_is_some.rs b/src/tools/clippy/clippy_lints/src/methods/search_is_some.rs index e9e654432208d..92a9764428d29 100644 --- a/src/tools/clippy/clippy_lints/src/methods/search_is_some.rs +++ b/src/tools/clippy/clippy_lints/src/methods/search_is_some.rs @@ -30,7 +30,7 @@ pub(super) fn check<'tcx>( search_method ); let hint = "this is more succinctly expressed by calling `any()`"; - let search_snippet = snippet(cx, search_args[1].span, ".."); + let search_snippet = snippet(cx, cx.tcx.hir().span(search_args[1].hir_id), ".."); if search_snippet.lines().count() <= 1 { // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()` // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()` @@ -56,7 +56,7 @@ pub(super) fn check<'tcx>( span_lint_and_sugg( cx, SEARCH_IS_SOME, - method_span.with_hi(expr.span.hi()), + method_span.with_hi(cx.tcx.hir().span(expr.hir_id).hi()), &msg, "use `any()` instead", format!( @@ -66,7 +66,7 @@ pub(super) fn check<'tcx>( Applicability::MachineApplicable, ); } else { - span_lint_and_help(cx, SEARCH_IS_SOME, expr.span, &msg, None, hint); + span_lint_and_help(cx, SEARCH_IS_SOME, cx.tcx.hir().span(expr.hir_id), &msg, None, hint); } } // lint if `find()` is called by `String` or `&str` @@ -85,11 +85,11 @@ pub(super) fn check<'tcx>( then { let msg = "called `is_some()` after calling `find()` on a string"; let mut applicability = Applicability::MachineApplicable; - let find_arg = snippet_with_applicability(cx, search_args[1].span, "..", &mut applicability); + let find_arg = snippet_with_applicability(cx, cx.tcx.hir().span(search_args[1].hir_id), "..", &mut applicability); span_lint_and_sugg( cx, SEARCH_IS_SOME, - method_span.with_hi(expr.span.hi()), + method_span.with_hi(cx.tcx.hir().span(expr.hir_id).hi()), msg, "use `contains()` instead", format!("contains({})", find_arg), diff --git a/src/tools/clippy/clippy_lints/src/methods/single_char_insert_string.rs b/src/tools/clippy/clippy_lints/src/methods/single_char_insert_string.rs index 0ce8b66978dc1..2982785e9e77f 100644 --- a/src/tools/clippy/clippy_lints/src/methods/single_char_insert_string.rs +++ b/src/tools/clippy/clippy_lints/src/methods/single_char_insert_string.rs @@ -10,14 +10,18 @@ use super::SINGLE_CHAR_ADD_STR; pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) { let mut applicability = Applicability::MachineApplicable; if let Some(extension_string) = get_hint_if_single_char_arg(cx, &args[2], &mut applicability) { - let base_string_snippet = - snippet_with_applicability(cx, args[0].span.source_callsite(), "_", &mut applicability); - let pos_arg = snippet_with_applicability(cx, args[1].span, "..", &mut applicability); + let base_string_snippet = snippet_with_applicability( + cx, + cx.tcx.hir().span(args[0].hir_id).source_callsite(), + "_", + &mut applicability, + ); + let pos_arg = snippet_with_applicability(cx, cx.tcx.hir().span(args[1].hir_id), "..", &mut applicability); let sugg = format!("{}.insert({}, {})", base_string_snippet, pos_arg, extension_string); span_lint_and_sugg( cx, SINGLE_CHAR_ADD_STR, - expr.span, + cx.tcx.hir().span(expr.hir_id), "calling `insert_str()` using a single-character string literal", "consider using `insert` with a character literal", sugg, diff --git a/src/tools/clippy/clippy_lints/src/methods/single_char_pattern.rs b/src/tools/clippy/clippy_lints/src/methods/single_char_pattern.rs index 61cbc9d2f0a62..82984c8e4bed5 100644 --- a/src/tools/clippy/clippy_lints/src/methods/single_char_pattern.rs +++ b/src/tools/clippy/clippy_lints/src/methods/single_char_pattern.rs @@ -13,7 +13,7 @@ pub(super) fn check(cx: &LateContext<'_>, _expr: &hir::Expr<'_>, arg: &hir::Expr span_lint_and_sugg( cx, SINGLE_CHAR_PATTERN, - arg.span, + cx.tcx.hir().span(arg.hir_id), "single-character string constant used as pattern", "try using a `char` instead", hint, diff --git a/src/tools/clippy/clippy_lints/src/methods/single_char_push_string.rs b/src/tools/clippy/clippy_lints/src/methods/single_char_push_string.rs index deacc70b713e5..3f2cd6c5975a2 100644 --- a/src/tools/clippy/clippy_lints/src/methods/single_char_push_string.rs +++ b/src/tools/clippy/clippy_lints/src/methods/single_char_push_string.rs @@ -10,13 +10,17 @@ use super::SINGLE_CHAR_ADD_STR; pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) { let mut applicability = Applicability::MachineApplicable; if let Some(extension_string) = get_hint_if_single_char_arg(cx, &args[1], &mut applicability) { - let base_string_snippet = - snippet_with_applicability(cx, args[0].span.source_callsite(), "..", &mut applicability); + let base_string_snippet = snippet_with_applicability( + cx, + cx.tcx.hir().span(args[0].hir_id).source_callsite(), + "..", + &mut applicability, + ); let sugg = format!("{}.push({})", base_string_snippet, extension_string); span_lint_and_sugg( cx, SINGLE_CHAR_ADD_STR, - expr.span, + cx.tcx.hir().span(expr.hir_id), "calling `push_str()` using a single-character string literal", "consider using `push` with a character literal", sugg, diff --git a/src/tools/clippy/clippy_lints/src/methods/skip_while_next.rs b/src/tools/clippy/clippy_lints/src/methods/skip_while_next.rs index 8ba6ae952003e..48cd6a53a9395 100644 --- a/src/tools/clippy/clippy_lints/src/methods/skip_while_next.rs +++ b/src/tools/clippy/clippy_lints/src/methods/skip_while_next.rs @@ -11,7 +11,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, _sk span_lint_and_help( cx, SKIP_WHILE_NEXT, - expr.span, + cx.tcx.hir().span(expr.hir_id), "called `skip_while(

).next()` on an `Iterator`", None, "this is more succinctly expressed by calling `.find(!

)` instead", diff --git a/src/tools/clippy/clippy_lints/src/methods/string_extend_chars.rs b/src/tools/clippy/clippy_lints/src/methods/string_extend_chars.rs index 0a08ea26175fe..e42addac23bf9 100644 --- a/src/tools/clippy/clippy_lints/src/methods/string_extend_chars.rs +++ b/src/tools/clippy/clippy_lints/src/methods/string_extend_chars.rs @@ -11,7 +11,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Exp let obj_ty = cx.typeck_results().expr_ty(&args[0]).peel_refs(); if is_type_diagnostic_item(cx, obj_ty, sym::string_type) { let arg = &args[1]; - if let Some(arglists) = method_chain_args(arg, &["chars"]) { + if let Some(arglists) = method_chain_args(cx, arg, &["chars"]) { let target = &arglists[0][0]; let self_ty = cx.typeck_results().expr_ty(target).peel_refs(); let ref_str = if *self_ty.kind() == ty::Str { @@ -26,14 +26,14 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Exp span_lint_and_sugg( cx, STRING_EXTEND_CHARS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "calling `.extend(_.chars())`", "try this", format!( "{}.push_str({}{})", - snippet_with_applicability(cx, args[0].span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(args[0].hir_id), "..", &mut applicability), ref_str, - snippet_with_applicability(cx, target.span, "..", &mut applicability) + snippet_with_applicability(cx, cx.tcx.hir().span(target.hir_id), "..", &mut applicability) ), applicability, ); diff --git a/src/tools/clippy/clippy_lints/src/methods/suspicious_map.rs b/src/tools/clippy/clippy_lints/src/methods/suspicious_map.rs index e135a826dc4d0..a00bd9fe7e3b1 100644 --- a/src/tools/clippy/clippy_lints/src/methods/suspicious_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/suspicious_map.rs @@ -8,7 +8,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>) { span_lint_and_help( cx, SUSPICIOUS_MAP, - expr.span, + cx.tcx.hir().span(expr.hir_id), "this call to `map()` won't have an effect on the call to `count()`", None, "make sure you did not confuse `map` with `filter` or `for_each`", diff --git a/src/tools/clippy/clippy_lints/src/methods/uninit_assumed_init.rs b/src/tools/clippy/clippy_lints/src/methods/uninit_assumed_init.rs index 798b66192c818..10ba8c38928c0 100644 --- a/src/tools/clippy/clippy_lints/src/methods/uninit_assumed_init.rs +++ b/src/tools/clippy/clippy_lints/src/methods/uninit_assumed_init.rs @@ -18,7 +18,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, outer: &hir::Exp span_lint( cx, UNINIT_ASSUMED_INIT, - outer.span, + cx.tcx.hir().span(outer.hir_id), "this call for this type may be undefined behavior" ); } diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs index 12b2cf0a16582..b4347c64ab8c0 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs @@ -31,7 +31,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Exp span_lint( cx, UNNECESSARY_FILTER_MAP, - expr.span, + cx.tcx.hir().span(expr.hir_id), "this `.filter_map` can be written more simply using `.map`", ); return; @@ -41,7 +41,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Exp span_lint( cx, UNNECESSARY_FILTER_MAP, - expr.span, + cx.tcx.hir().span(expr.hir_id), "this `.filter_map` can be written more simply using `.filter`", ); return; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs index a26443f4ee944..1948cfdbf2386 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs @@ -47,7 +47,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, fold_args: &[hir "{replacement}(|{s}| {r})", replacement = replacement_method_name, s = second_arg_ident, - r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability), + r = snippet_with_applicability(cx, cx.tcx.hir().span(right_expr.hir_id), "EXPR", &mut applicability), ) } else { format!( @@ -59,7 +59,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, fold_args: &[hir span_lint_and_sugg( cx, UNNECESSARY_FOLD, - fold_span.with_hi(expr.span.hi()), + fold_span.with_hi(cx.tcx.hir().span(expr.hir_id).hi()), // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f) "this `.fold` can be written more succinctly using another method", "try", diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_lazy_eval.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_lazy_eval.rs index a17259d697faa..d3206c0c1ed1c 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_lazy_eval.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_lazy_eval.rs @@ -48,14 +48,14 @@ pub(super) fn check<'tcx>( span_lint_and_sugg( cx, UNNECESSARY_LAZY_EVALUATIONS, - expr.span, + cx.tcx.hir().span(expr.hir_id), msg, &format!("use `{}` instead", simplify_using), format!( "{0}.{1}({2})", - snippet(cx, args[0].span, ".."), + snippet(cx, cx.tcx.hir().span(args[0].hir_id), ".."), simplify_using, - snippet(cx, body_expr.span, ".."), + snippet(cx, cx.tcx.hir().span(body_expr.hir_id), ".."), ), applicability, ); diff --git a/src/tools/clippy/clippy_lints/src/methods/unwrap_used.rs b/src/tools/clippy/clippy_lints/src/methods/unwrap_used.rs index 094c3fc45c493..438320c6bf5ff 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unwrap_used.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unwrap_used.rs @@ -21,7 +21,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, unwrap_args: &[h span_lint_and_help( cx, lint, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("used `unwrap()` on `{}` value", kind,), None, &format!( diff --git a/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs b/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs index e4554f8d4897e..cba45b9120a49 100644 --- a/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs +++ b/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs @@ -24,7 +24,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, call_name: &str, if_chain! { if let Some(parent) = get_parent_expr(cx, expr); if let hir::ExprKind::MethodCall(_, ref span, _, _) = parent.kind; - if span != &expr.span; + if span != &cx.tcx.hir().span(expr.hir_id); then { return; } @@ -34,10 +34,10 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, call_name: &str, span_lint_and_sugg( cx, USELESS_ASREF, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("this call to `{}` does nothing", call_name), "try this", - snippet_with_applicability(cx, recvr.span, "..", &mut applicability).to_string(), + snippet_with_applicability(cx, cx.tcx.hir().span(recvr.hir_id), "..", &mut applicability).to_string(), applicability, ); } diff --git a/src/tools/clippy/clippy_lints/src/methods/zst_offset.rs b/src/tools/clippy/clippy_lints/src/methods/zst_offset.rs index f1335726736ca..5a609e97650b8 100644 --- a/src/tools/clippy/clippy_lints/src/methods/zst_offset.rs +++ b/src/tools/clippy/clippy_lints/src/methods/zst_offset.rs @@ -13,7 +13,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Exp if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty)); if layout.is_zst(); then { - span_lint(cx, ZST_OFFSET, expr.span, "offset calculation on zero-sized value"); + span_lint(cx, ZST_OFFSET, cx.tcx.hir().span(expr.hir_id), "offset calculation on zero-sized value"); } } } diff --git a/src/tools/clippy/clippy_lints/src/minmax.rs b/src/tools/clippy/clippy_lints/src/minmax.rs index 8d0c3b8e0fe89..6fd4b89a3968e 100644 --- a/src/tools/clippy/clippy_lints/src/minmax.rs +++ b/src/tools/clippy/clippy_lints/src/minmax.rs @@ -48,7 +48,7 @@ impl<'tcx> LateLintPass<'tcx> for MinMaxPass { span_lint( cx, MIN_MAX, - expr.span, + cx.tcx.hir().span(expr.hir_id), "this `min`/`max` combination leads to constant result", ); }, diff --git a/src/tools/clippy/clippy_lints/src/misc.rs b/src/tools/clippy/clippy_lints/src/misc.rs index 40a534af2fe12..c44fabe3bf243 100644 --- a/src/tools/clippy/clippy_lints/src/misc.rs +++ b/src/tools/clippy/clippy_lints/src/misc.rs @@ -312,7 +312,7 @@ impl<'tcx> LateLintPass<'tcx> for MiscLints { // 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 local_span = cx.tcx.hir().span(local.hir_id); - let sugg_init = if init.span.from_expansion() && !local_span.from_expansion() { + let sugg_init = if cx.tcx.hir().span(init.hir_id).from_expansion() && !local_span.from_expansion() { Sugg::hir_with_macro_callsite(cx, init, "..") } else { Sugg::hir(cx, init, "..") @@ -370,7 +370,7 @@ impl<'tcx> LateLintPass<'tcx> for MiscLints { format!( "if {} {{ {}; }}", sugg, - &snippet(cx, b.span, ".."), + &snippet(cx, cx.tcx.hir().span(b.hir_id), ".."), ), Applicability::MachineApplicable, // snippet ); @@ -380,9 +380,10 @@ impl<'tcx> LateLintPass<'tcx> for MiscLints { } fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { + let expr_span = cx.tcx.hir().span(expr.hir_id); match expr.kind { ExprKind::Cast(ref e, ref ty) => { - check_cast(cx, expr.span, e, ty); + check_cast(cx, expr_span, e, ty); return; }, ExprKind::Binary(ref cmp, ref left, ref right) => { @@ -391,7 +392,7 @@ impl<'tcx> LateLintPass<'tcx> for MiscLints { }, _ => {}, } - if in_attributes_expansion(expr) || expr.span.is_desugaring(DesugaringKind::Await) { + if in_attributes_expansion(cx, expr) || expr_span.is_desugaring(DesugaringKind::Await) { // Don't lint things expanded by #[derive(...)], etc or `await` desugaring return; } @@ -424,7 +425,7 @@ impl<'tcx> LateLintPass<'tcx> for MiscLints { span_lint( cx, USED_UNDERSCORE_BINDING, - expr.span, + expr_span, &format!( "used binding `{}` which is prefixed with an underscore. A leading \ underscore signals that a binding will not be used", @@ -475,7 +476,7 @@ fn check_nan(cx: &LateContext<'_>, expr: &Expr<'_>, cmp_expr: &Expr<'_>) { span_lint( cx, CMP_NAN, - cmp_expr.span, + cx.tcx.hir().span(cmp_expr.hir_id), "doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead", ); } @@ -564,7 +565,7 @@ fn check_to_owned(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left: if is_diagnostic_assoc_item(cx, expr_def_id, sym::ToString) || is_diagnostic_assoc_item(cx, expr_def_id, sym::ToOwned); then { - (cx.typeck_results().expr_ty(&args[0]), snippet(cx, args[0].span, "..")) + (cx.typeck_results().expr_ty(&args[0]), snippet(cx, cx.tcx.hir().span(args[0].hir_id), "..")) } else { return; } @@ -573,7 +574,10 @@ fn check_to_owned(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left: ExprKind::Call(ref path, ref v) if v.len() == 1 => { if let ExprKind::Path(ref path) = path.kind { if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) { - (cx.typeck_results().expr_ty(&v[0]), snippet(cx, v[0].span, "..")) + ( + cx.typeck_results().expr_ty(&v[0]), + snippet(cx, cx.tcx.hir().span(v[0].hir_id), ".."), + ) } else { return; } @@ -599,9 +603,9 @@ fn check_to_owned(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left: let other_gets_derefed = matches!(other.kind, ExprKind::Unary(UnOp::Deref, _)); let lint_span = if other_gets_derefed { - expr.span.to(other.span) + cx.tcx.hir().span(expr.hir_id).to(cx.tcx.hir().span(other.hir_id)) } else { - expr.span + cx.tcx.hir().span(expr.hir_id) }; span_lint_and_then( @@ -626,17 +630,20 @@ fn check_to_owned(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left: eq_impl = without_deref; }; + let expr_span = cx.tcx.hir().span(expr.hir_id); + let other_span = cx.tcx.hir().span(other.hir_id); + let span; let hint; if (eq_impl.ty_eq_other && left) || (eq_impl.other_eq_ty && !left) { - span = expr.span; + span = expr_span; hint = expr_snip; } else { - span = expr.span.to(other.span); + span = expr_span.to(other_span); if eq_impl.ty_eq_other { - hint = format!("{} == {}", expr_snip, snippet(cx, other.span, "..")); + hint = format!("{} == {}", expr_snip, snippet(cx, other_span, "..")); } else { - hint = format!("{} == {}", snippet(cx, other.span, ".."), expr_snip); + hint = format!("{} == {}", snippet(cx, other_span, ".."), expr_snip); } } @@ -662,11 +669,17 @@ fn is_used(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { /// Tests whether an expression is in a macro expansion (e.g., something /// generated by `#[derive(...)]` or the like). -fn in_attributes_expansion(expr: &Expr<'_>) -> bool { +fn in_attributes_expansion(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { use rustc_span::hygiene::MacroKind; - if expr.span.from_expansion() { - let data = expr.span.ctxt().outer_expn_data(); - matches!(data.kind, ExpnKind::Macro(MacroKind::Attr, _)) + let expr_span = cx.tcx.hir().span(expr.hir_id); + if expr_span.from_expansion() { + let data = expr_span.ctxt().outer_expn_data(); + + if let ExpnKind::Macro(MacroKind::Attr, _) = data.kind { + true + } else { + false + } } else { false } @@ -741,13 +754,14 @@ fn check_binary( is_named_constant(cx, left) || is_named_constant(cx, right), is_comparing_arrays, ); - span_lint_and_then(cx, lint, expr.span, msg, |diag| { + let expr_span = cx.tcx.hir().span(expr.hir_id); + span_lint_and_then(cx, lint, expr_span, msg, |diag| { let lhs = Sugg::hir(cx, left, ".."); let rhs = Sugg::hir(cx, right, ".."); if !is_comparing_arrays { diag.span_suggestion( - expr.span, + expr_span, "consider comparing them within some margin of error", format!( "({}).abs() {} error_margin", @@ -760,8 +774,9 @@ fn check_binary( diag.note("`f32::EPSILON` and `f64::EPSILON` are available for the `error_margin`"); }); } else if op == BinOpKind::Rem { + let expr_span = cx.tcx.hir().span(expr.hir_id); if is_integer_const(cx, right, 1) { - span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0"); + span_lint(cx, MODULO_ONE, expr_span, "any number modulo 1 will be 0"); } if let ty::Int(ity) = cx.typeck_results().expr_ty(right).kind() { @@ -769,7 +784,7 @@ fn check_binary( span_lint( cx, MODULO_ONE, - expr.span, + expr_span, "any number modulo -1 will panic/overflow or result in 0", ); } diff --git a/src/tools/clippy/clippy_lints/src/modulo_arithmetic.rs b/src/tools/clippy/clippy_lints/src/modulo_arithmetic.rs index da3ae1d652f6c..8cf0567dd34fc 100644 --- a/src/tools/clippy/clippy_lints/src/modulo_arithmetic.rs +++ b/src/tools/clippy/clippy_lints/src/modulo_arithmetic.rs @@ -89,7 +89,7 @@ fn check_const_operands<'tcx>( span_lint_and_then( cx, MODULO_ARITHMETIC, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!( "you are using modulo operator on constants with different signs: `{} % {}`", lhs_operand.string_representation.as_ref().unwrap(), @@ -111,7 +111,7 @@ fn check_non_const_operands<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, span_lint_and_then( cx, MODULO_ARITHMETIC, - expr.span, + cx.tcx.hir().span(expr.hir_id), "you are using modulo operator on types that might have different signs", |diag| { diag.note("double check for expected result especially when interoperating with different languages"); diff --git a/src/tools/clippy/clippy_lints/src/mut_mut.rs b/src/tools/clippy/clippy_lints/src/mut_mut.rs index 196e67209f4a2..c66e838945480 100644 --- a/src/tools/clippy/clippy_lints/src/mut_mut.rs +++ b/src/tools/clippy/clippy_lints/src/mut_mut.rs @@ -48,7 +48,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> { type Map = Map<'tcx>; fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) { - if in_external_macro(self.cx.sess(), expr.span) { + if in_external_macro(self.cx.sess(), self.cx.tcx.hir().span(expr.hir_id)) { return; } @@ -66,14 +66,14 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> { span_lint( self.cx, MUT_MUT, - expr.span, + self.cx.tcx.hir().span(expr.hir_id), "generally you want to avoid `&mut &mut _` if possible", ); } else if let ty::Ref(_, _, hir::Mutability::Mut) = self.cx.typeck_results().expr_ty(e).kind() { span_lint( self.cx, MUT_MUT, - expr.span, + self.cx.tcx.hir().span(expr.hir_id), "this expression mutably borrows a mutable reference. Consider reborrowing", ); } diff --git a/src/tools/clippy/clippy_lints/src/mut_reference.rs b/src/tools/clippy/clippy_lints/src/mut_reference.rs index 3f0b765df1561..7ef9d7eaa17c2 100644 --- a/src/tools/clippy/clippy_lints/src/mut_reference.rs +++ b/src/tools/clippy/clippy_lints/src/mut_reference.rs @@ -74,7 +74,7 @@ fn check_arguments<'tcx>( span_lint( cx, UNNECESSARY_MUT_PASSED, - argument.span, + cx.tcx.hir().span(argument.hir_id), &format!("the {} `{}` doesn't need a mutable reference", fn_kind, name), ); } diff --git a/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs b/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs index 9caacb5db7c9c..08b207529e863 100644 --- a/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs +++ b/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs @@ -37,7 +37,7 @@ const DEBUG_MACRO_NAMES: [&str; 3] = ["debug_assert", "debug_assert_eq", "debug_ impl<'tcx> LateLintPass<'tcx> for DebugAssertWithMutCall { fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { for dmn in &DEBUG_MACRO_NAMES { - if is_direct_expn_of(e.span, dmn).is_some() { + if is_direct_expn_of(cx.tcx.hir().span(e.hir_id), dmn).is_some() { if let Some(macro_args) = higher::extract_assert_macro_args(e) { for arg in macro_args { let mut visitor = MutArgVisitor::new(cx); @@ -103,7 +103,7 @@ impl<'a, 'tcx> Visitor<'tcx> for MutArgVisitor<'a, 'tcx> { }, // Don't check await desugars ExprKind::Match(_, _, MatchSource::AwaitDesugar) => return, - _ if !self.found => self.expr_span = Some(expr.span), + _ if !self.found => self.expr_span = Some(self.cx.tcx.hir().span(expr.hir_id)), _ => return, } walk_expr(self, expr) diff --git a/src/tools/clippy/clippy_lints/src/mutex_atomic.rs b/src/tools/clippy/clippy_lints/src/mutex_atomic.rs index 40b236493a313..2faf180cd8a1a 100644 --- a/src/tools/clippy/clippy_lints/src/mutex_atomic.rs +++ b/src/tools/clippy/clippy_lints/src/mutex_atomic.rs @@ -75,10 +75,11 @@ impl<'tcx> LateLintPass<'tcx> for Mutex { behavior and not the internal type, consider using `Mutex<()>`", atomic_name ); + let expr_span = cx.tcx.hir().span(expr.hir_id); match *mutex_param.kind() { - ty::Uint(t) if t != ty::UintTy::Usize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg), - ty::Int(t) if t != ty::IntTy::Isize => span_lint(cx, MUTEX_INTEGER, expr.span, &msg), - _ => span_lint(cx, MUTEX_ATOMIC, expr.span, &msg), + ty::Uint(t) if t != ty::UintTy::Usize => span_lint(cx, MUTEX_INTEGER, expr_span, &msg), + ty::Int(t) if t != ty::IntTy::Isize => span_lint(cx, MUTEX_INTEGER, expr_span, &msg), + _ => span_lint(cx, MUTEX_ATOMIC, expr_span, &msg), }; } } diff --git a/src/tools/clippy/clippy_lints/src/needless_bool.rs b/src/tools/clippy/clippy_lints/src/needless_bool.rs index f283ff1715fb6..c73dc88f492ed 100644 --- a/src/tools/clippy/clippy_lints/src/needless_bool.rs +++ b/src/tools/clippy/clippy_lints/src/needless_bool.rs @@ -86,7 +86,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessBool { span_lint_and_sugg( cx, NEEDLESS_BOOL, - e.span, + cx.tcx.hir().span(e.hir_id), "this if-then-else expression returns a bool literal", "you can reduce it to", snip.to_string(), @@ -99,7 +99,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessBool { span_lint( cx, NEEDLESS_BOOL, - e.span, + cx.tcx.hir().span(e.hir_id), "this if-then-else expression will always return true", ); }, @@ -107,7 +107,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessBool { span_lint( cx, NEEDLESS_BOOL, - e.span, + cx.tcx.hir().span(e.hir_id), "this if-then-else expression will always return false", ); }, @@ -128,7 +128,7 @@ declare_lint_pass!(BoolComparison => [BOOL_COMPARISON]); impl<'tcx> LateLintPass<'tcx> for BoolComparison { fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { - if e.span.from_expansion() { + if cx.tcx.hir().span(e.hir_id).from_expansion() { return; } @@ -194,16 +194,20 @@ struct ExpressionInfoWithSpan { right_span: Span, } -fn is_unary_not(e: &Expr<'_>) -> (bool, Span) { +fn is_unary_not(cx: &LateContext<'_>, e: &Expr<'_>) -> (bool, Span) { if let ExprKind::Unary(UnOp::Not, operand) = e.kind { - return (true, operand.span); + return (true, cx.tcx.hir().span(operand.hir_id)); } - (false, e.span) + (false, cx.tcx.hir().span(e.hir_id)) } -fn one_side_is_unary_not<'tcx>(left_side: &'tcx Expr<'_>, right_side: &'tcx Expr<'_>) -> ExpressionInfoWithSpan { - let left = is_unary_not(left_side); - let right = is_unary_not(right_side); +fn one_side_is_unary_not<'tcx>( + cx: &LateContext<'tcx>, + left_side: &'tcx Expr<'_>, + right_side: &'tcx Expr<'_>, +) -> ExpressionInfoWithSpan { + let left = is_unary_not(cx, left_side); + let right = is_unary_not(cx, right_side); ExpressionInfoWithSpan { one_side_is_unary_not: left.0 != right.0, @@ -228,19 +232,21 @@ fn check_comparison<'a, 'tcx>( cx.typeck_results().expr_ty(left_side), cx.typeck_results().expr_ty(right_side), ); - if is_expn_of(left_side.span, "cfg").is_some() || is_expn_of(right_side.span, "cfg").is_some() { + if is_expn_of(cx.tcx.hir().span(left_side.hir_id), "cfg").is_some() + || is_expn_of(cx.tcx.hir().span(right_side.hir_id), "cfg").is_some() + { return; } if l_ty.is_bool() && r_ty.is_bool() { let mut applicability = Applicability::MachineApplicable; if let BinOpKind::Eq = op.node { - let expression_info = one_side_is_unary_not(&left_side, &right_side); + let expression_info = one_side_is_unary_not(cx, &left_side, &right_side); if expression_info.one_side_is_unary_not { span_lint_and_sugg( cx, BOOL_COMPARISON, - e.span, + cx.tcx.hir().span(e.hir_id), "this comparison might be written more concisely", "try simplifying it as shown", format!( @@ -272,7 +278,7 @@ fn check_comparison<'a, 'tcx>( span_lint_and_sugg( cx, BOOL_COMPARISON, - e.span, + cx.tcx.hir().span(e.hir_id), m, "try simplifying it as shown", h(left_side, right_side).to_string(), @@ -293,7 +299,7 @@ fn suggest_bool_comparison<'a, 'tcx>( message: &str, conv_hint: impl FnOnce(Sugg<'a>) -> Sugg<'a>, ) { - let hint = if expr.span.from_expansion() { + let hint = if cx.tcx.hir().span(expr.hir_id).from_expansion() { if applicability != Applicability::Unspecified { applicability = Applicability::MaybeIncorrect; } @@ -304,7 +310,7 @@ fn suggest_bool_comparison<'a, 'tcx>( span_lint_and_sugg( cx, BOOL_COMPARISON, - e.span, + cx.tcx.hir().span(e.hir_id), message, "try simplifying it as shown", conv_hint(hint).to_string(), diff --git a/src/tools/clippy/clippy_lints/src/needless_borrow.rs b/src/tools/clippy/clippy_lints/src/needless_borrow.rs index 5f8ed414db2ee..74083756d9546 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrow.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrow.rs @@ -43,7 +43,8 @@ impl_lint_pass!(NeedlessBorrow => [NEEDLESS_BORROW]); impl<'tcx> LateLintPass<'tcx> for NeedlessBorrow { fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { - if e.span.from_expansion() || self.derived_item.is_some() { + let e_span = cx.tcx.hir().span(e.hir_id); + if e_span.from_expansion() || self.derived_item.is_some() { return; } if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = e.kind { @@ -61,16 +62,16 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessBorrow { span_lint_and_then( cx, NEEDLESS_BORROW, - e.span, + e_span, &format!( "this expression borrows a reference (`&{}`) that is immediately dereferenced \ by the compiler", ty ), |diag| { - if let Some(snippet) = snippet_opt(cx, inner.span) { + if let Some(snippet) = snippet_opt(cx, cx.tcx.hir().span(inner.hir_id)) { diag.span_suggestion( - e.span, + e_span, "change this to", snippet, Applicability::MachineApplicable, diff --git a/src/tools/clippy/clippy_lints/src/needless_question_mark.rs b/src/tools/clippy/clippy_lints/src/needless_question_mark.rs index a3293f1b36149..9fdf834b93321 100644 --- a/src/tools/clippy/clippy_lints/src/needless_question_mark.rs +++ b/src/tools/clippy/clippy_lints/src/needless_question_mark.rs @@ -141,10 +141,13 @@ fn emit_lint(cx: &LateContext<'_>, expr: &SomeOkCall<'_>) { utils::span_lint_and_sugg( cx, NEEDLESS_QUESTION_MARK, - entire_expr.span, + cx.tcx.hir().span(entire_expr.hir_id), "question mark operator is useless here", "try", - format!("{}", utils::snippet(cx, inner_expr.span, r#""...""#)), + format!( + "{}", + utils::snippet(cx, cx.tcx.hir().span(inner_expr.hir_id), r#""...""#) + ), Applicability::MachineApplicable, ); } diff --git a/src/tools/clippy/clippy_lints/src/needless_update.rs b/src/tools/clippy/clippy_lints/src/needless_update.rs index 41cf541ecf5ef..70d4a5cf1c221 100644 --- a/src/tools/clippy/clippy_lints/src/needless_update.rs +++ b/src/tools/clippy/clippy_lints/src/needless_update.rs @@ -58,7 +58,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessUpdate { span_lint( cx, NEEDLESS_UPDATE, - base.span, + cx.tcx.hir().span(base.hir_id), "struct update has no effect, all the fields in the struct have already been specified", ); } diff --git a/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs b/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs index ec0ad58ca9c3e..221801d417ea9 100644 --- a/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs +++ b/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs @@ -49,7 +49,7 @@ impl<'tcx> LateLintPass<'tcx> for NoNegCompOpForPartialOrd { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if_chain! { - if !in_external_macro(cx.sess(), expr.span); + if !in_external_macro(cx.sess(), cx.tcx.hir().span(expr.hir_id)); if let ExprKind::Unary(UnOp::Not, ref inner) = expr.kind; if let ExprKind::Binary(ref op, ref left, _) = inner.kind; if let BinOpKind::Le | BinOpKind::Ge | BinOpKind::Lt | BinOpKind::Gt = op.node; @@ -78,7 +78,7 @@ impl<'tcx> LateLintPass<'tcx> for NoNegCompOpForPartialOrd { span_lint( cx, NEG_CMP_OP_ON_PARTIAL_ORD, - expr.span, + cx.tcx.hir().span(expr.hir_id), "the use of negated comparison operators on partially ordered \ types produces code that is hard to read and refactor, please \ consider using the `partial_cmp` method instead, to make it \ diff --git a/src/tools/clippy/clippy_lints/src/neg_multiply.rs b/src/tools/clippy/clippy_lints/src/neg_multiply.rs index ef7cc65cfcf0a..0f79dbe13ace7 100644 --- a/src/tools/clippy/clippy_lints/src/neg_multiply.rs +++ b/src/tools/clippy/clippy_lints/src/neg_multiply.rs @@ -32,8 +32,8 @@ impl<'tcx> LateLintPass<'tcx> for NegMultiply { if BinOpKind::Mul == op.node { match (&left.kind, &right.kind) { (&ExprKind::Unary(..), &ExprKind::Unary(..)) => {}, - (&ExprKind::Unary(UnOp::Neg, ref lit), _) => check_mul(cx, e.span, lit, right), - (_, &ExprKind::Unary(UnOp::Neg, ref lit)) => check_mul(cx, e.span, lit, left), + (&ExprKind::Unary(UnOp::Neg, ref lit), _) => check_mul(cx, cx.tcx.hir().span(e.hir_id), lit, right), + (_, &ExprKind::Unary(UnOp::Neg, ref lit)) => check_mul(cx, cx.tcx.hir().span(e.hir_id), lit, left), _ => {}, } } diff --git a/src/tools/clippy/clippy_lints/src/no_effect.rs b/src/tools/clippy/clippy_lints/src/no_effect.rs index 7202f2e4c525c..d958bf16bf0d1 100644 --- a/src/tools/clippy/clippy_lints/src/no_effect.rs +++ b/src/tools/clippy/clippy_lints/src/no_effect.rs @@ -43,7 +43,7 @@ declare_clippy_lint! { } fn has_no_effect(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { - if expr.span.from_expansion() { + if cx.tcx.hir().span(expr.hir_id).from_expansion() { return false; } match expr.kind { @@ -96,10 +96,10 @@ impl<'tcx> LateLintPass<'tcx> for NoEffect { } else if let Some(reduced) = reduce_expression(cx, expr) { let mut snippet = String::new(); for e in reduced { - if e.span.from_expansion() { + if cx.tcx.hir().span(e.hir_id).from_expansion() { return; } - if let Some(snip) = snippet_opt(cx, e.span) { + if let Some(snip) = snippet_opt(cx, cx.tcx.hir().span(e.hir_id)) { snippet.push_str(&snip); snippet.push(';'); } else { @@ -121,7 +121,7 @@ impl<'tcx> LateLintPass<'tcx> for NoEffect { } fn reduce_expression<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option>> { - if expr.span.from_expansion() { + if cx.tcx.hir().span(expr.hir_id).from_expansion() { return None; } match expr.kind { diff --git a/src/tools/clippy/clippy_lints/src/non_copy_const.rs b/src/tools/clippy/clippy_lints/src/non_copy_const.rs index 9bda9d8e0a5e4..454a0e44e0ee8 100644 --- a/src/tools/clippy/clippy_lints/src/non_copy_const.rs +++ b/src/tools/clippy/clippy_lints/src/non_copy_const.rs @@ -418,7 +418,7 @@ impl<'tcx> LateLintPass<'tcx> for NonCopyConst { }; if is_unfrozen(cx, ty) && is_value_unfrozen_expr(cx, expr.hir_id, item_def_id, ty) { - lint(cx, Source::Expr { expr: expr.span }); + lint(cx, Source::Expr { expr: cx.tcx.hir().span(expr.hir_id) }); } } } diff --git a/src/tools/clippy/clippy_lints/src/open_options.rs b/src/tools/clippy/clippy_lints/src/open_options.rs index 07ca196990da9..c90800c2eb736 100644 --- a/src/tools/clippy/clippy_lints/src/open_options.rs +++ b/src/tools/clippy/clippy_lints/src/open_options.rs @@ -34,7 +34,7 @@ impl<'tcx> LateLintPass<'tcx> for OpenOptions { if path.ident.name == sym!(open) && match_type(cx, obj_ty, &paths::OPEN_OPTIONS) { let mut options = Vec::new(); get_open_options(cx, &arguments[0], &mut options); - check_open_options(cx, &options, e.span); + check_open_options(cx, &options, cx.tcx.hir().span(e.hir_id)); } } } diff --git a/src/tools/clippy/clippy_lints/src/option_if_let_else.rs b/src/tools/clippy/clippy_lints/src/option_if_let_else.rs index 9ef0d267b0b20..a3a6eac99f036 100644 --- a/src/tools/clippy/clippy_lints/src/option_if_let_else.rs +++ b/src/tools/clippy/clippy_lints/src/option_if_let_else.rs @@ -158,15 +158,15 @@ fn detect_option_if_let_else<'tcx>( expr: &'_ Expr<'tcx>, ) -> Option { if_chain! { - if !utils::in_macro(expr.span); // Don't lint macros, because it behaves weirdly + if !utils::in_macro(cx.tcx.hir().span(expr.hir_id)); // Don't lint macros, because it behaves weirdly if let ExprKind::Match(cond_expr, arms, MatchSource::IfLetDesugar{contains_else_clause: true}) = &expr.kind; if arms.len() == 2; if !is_result_ok(cx, cond_expr); // Don't lint on Result::ok because a different lint does it already if let PatKind::TupleStruct(struct_qpath, &[inner_pat], _) = &arms[0].pat.kind; if utils::match_qpath(struct_qpath, &paths::OPTION_SOME); if let PatKind::Binding(bind_annotation, _, id, _) = &inner_pat.kind; - if !utils::usage::contains_return_break_continue_macro(arms[0].body); - if !utils::usage::contains_return_break_continue_macro(arms[1].body); + if !utils::usage::contains_return_break_continue_macro(cx, arms[0].body); + if !utils::usage::contains_return_break_continue_macro(cx, arms[1].body); then { let capture_mut = if bind_annotation == &BindingAnnotation::Mutable { "mut " } else { "" }; let some_body = extract_body_from_arm(&arms[0])?; @@ -203,7 +203,7 @@ impl<'tcx> LateLintPass<'tcx> for OptionIfLetElse { span_lint_and_sugg( cx, OPTION_IF_LET_ELSE, - expr.span, + cx.tcx.hir().span(expr.hir_id), format!("use Option::{} instead of an if let/else", detection.method_sugg).as_str(), "try", format!( diff --git a/src/tools/clippy/clippy_lints/src/overflow_check_conditional.rs b/src/tools/clippy/clippy_lints/src/overflow_check_conditional.rs index 3c041bac234a5..555f4235e9a5d 100644 --- a/src/tools/clippy/clippy_lints/src/overflow_check_conditional.rs +++ b/src/tools/clippy/clippy_lints/src/overflow_check_conditional.rs @@ -41,13 +41,13 @@ impl<'tcx> LateLintPass<'tcx> for OverflowCheckConditional { then { if let BinOpKind::Lt = op.node { if let BinOpKind::Add = op2.node { - span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span, + span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, cx.tcx.hir().span(expr.hir_id), "you are trying to use classic C overflow conditions that will fail in Rust"); } } if let BinOpKind::Gt = op.node { if let BinOpKind::Sub = op2.node { - span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span, + span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, cx.tcx.hir().span(expr.hir_id), "you are trying to use classic C underflow conditions that will fail in Rust"); } } @@ -66,13 +66,13 @@ impl<'tcx> LateLintPass<'tcx> for OverflowCheckConditional { then { if let BinOpKind::Gt = op.node { if let BinOpKind::Add = op2.node { - span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span, + span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, cx.tcx.hir().span(expr.hir_id), "you are trying to use classic C overflow conditions that will fail in Rust"); } } if let BinOpKind::Lt = op.node { if let BinOpKind::Sub = op2.node { - span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, expr.span, + span_lint(cx, OVERFLOW_CHECK_CONDITIONAL, cx.tcx.hir().span(expr.hir_id), "you are trying to use classic C underflow conditions that will fail in Rust"); } } 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 9cf6ffe90f447..e0b5d6754da17 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 @@ -51,6 +51,7 @@ impl<'tcx> LateLintPass<'tcx> for PanicInResultFn { fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, body: &'tcx hir::Body<'tcx>) { let panics = find_macro_calls( + cx.tcx, &[ "unimplemented", "unreachable", diff --git a/src/tools/clippy/clippy_lints/src/panic_unimplemented.rs b/src/tools/clippy/clippy_lints/src/panic_unimplemented.rs index 359620cc07975..15a62293fc0ba 100644 --- a/src/tools/clippy/clippy_lints/src/panic_unimplemented.rs +++ b/src/tools/clippy/clippy_lints/src/panic_unimplemented.rs @@ -74,35 +74,37 @@ declare_lint_pass!(PanicUnimplemented => [UNIMPLEMENTED, UNREACHABLE, TODO, PANI impl<'tcx> LateLintPass<'tcx> for PanicUnimplemented { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if match_panic_call(cx, expr).is_some() { - let span = get_outer_span(expr); - if is_expn_of(expr.span, "unimplemented").is_some() { + let span = get_outer_span(cx, expr); + let expr_span = cx.tcx.hir().span(expr.hir_id); + if is_expn_of(expr_span, "unimplemented").is_some() { span_lint( cx, UNIMPLEMENTED, span, "`unimplemented` should not be present in production code", ); - } else if is_expn_of(expr.span, "todo").is_some() { + } else if is_expn_of(expr_span, "todo").is_some() { span_lint(cx, TODO, span, "`todo` should not be present in production code"); - } else if is_expn_of(expr.span, "unreachable").is_some() { + } else if is_expn_of(expr_span, "unreachable").is_some() { span_lint(cx, UNREACHABLE, span, "usage of the `unreachable!` macro"); - } else if is_expn_of(expr.span, "panic").is_some() { + } else if is_expn_of(expr_span, "panic").is_some() { span_lint(cx, PANIC, span, "`panic` should not be present in production code"); } } } } -fn get_outer_span(expr: &Expr<'_>) -> Span { +fn get_outer_span(cx: &LateContext<'_>, expr: &Expr<'_>) -> Span { + let expr_span = cx.tcx.hir().span(expr.hir_id); if_chain! { - if expr.span.from_expansion(); - let first = expr.span.ctxt().outer_expn_data(); + if expr_span.from_expansion(); + let first = expr_span.ctxt().outer_expn_data(); if first.call_site.from_expansion(); let second = first.call_site.ctxt().outer_expn_data(); then { second.call_site } else { - expr.span + expr_span } } } diff --git a/src/tools/clippy/clippy_lints/src/ptr.rs b/src/tools/clippy/clippy_lints/src/ptr.rs index 51897fad69b23..1758d36c09930 100644 --- a/src/tools/clippy/clippy_lints/src/ptr.rs +++ b/src/tools/clippy/clippy_lints/src/ptr.rs @@ -157,7 +157,7 @@ impl<'tcx> LateLintPass<'tcx> for Ptr { span_lint( cx, CMP_NULL, - expr.span, + cx.tcx.hir().span(expr.hir_id), "comparing with null is better expressed by the `.is_null()` method", ); } diff --git a/src/tools/clippy/clippy_lints/src/ptr_eq.rs b/src/tools/clippy/clippy_lints/src/ptr_eq.rs index 3be792ce5e4fa..01babb3dd2be7 100644 --- a/src/tools/clippy/clippy_lints/src/ptr_eq.rs +++ b/src/tools/clippy/clippy_lints/src/ptr_eq.rs @@ -40,7 +40,7 @@ static LINT_MSG: &str = "use `std::ptr::eq` when comparing raw pointers"; impl LateLintPass<'_> for PtrEq { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if utils::in_macro(expr.span) { + if utils::in_macro(cx.tcx.hir().span(expr.hir_id)) { return; } @@ -54,13 +54,13 @@ impl LateLintPass<'_> for PtrEq { if_chain! { if let Some(left_var) = expr_as_cast_to_raw_pointer(cx, left); if let Some(right_var) = expr_as_cast_to_raw_pointer(cx, right); - if let Some(left_snip) = utils::snippet_opt(cx, left_var.span); - if let Some(right_snip) = utils::snippet_opt(cx, right_var.span); + if let Some(left_snip) = utils::snippet_opt(cx, cx.tcx.hir().span(left_var.hir_id)); + if let Some(right_snip) = utils::snippet_opt(cx, cx.tcx.hir().span(right_var.hir_id)); then { utils::span_lint_and_sugg( cx, PTR_EQ, - expr.span, + cx.tcx.hir().span(expr.hir_id), LINT_MSG, "try", format!("std::ptr::eq({}, {})", left_snip, right_snip), diff --git a/src/tools/clippy/clippy_lints/src/ptr_offset_with_cast.rs b/src/tools/clippy/clippy_lints/src/ptr_offset_with_cast.rs index e0996804a5934..497d967e47305 100644 --- a/src/tools/clippy/clippy_lints/src/ptr_offset_with_cast.rs +++ b/src/tools/clippy/clippy_lints/src/ptr_offset_with_cast.rs @@ -63,14 +63,14 @@ impl<'tcx> LateLintPass<'tcx> for PtrOffsetWithCast { span_lint_and_sugg( cx, PTR_OFFSET_WITH_CAST, - expr.span, + cx.tcx.hir().span(expr.hir_id), &msg, "try", sugg, Applicability::MachineApplicable, ); } else { - span_lint(cx, PTR_OFFSET_WITH_CAST, expr.span, &msg); + span_lint(cx, PTR_OFFSET_WITH_CAST, cx.tcx.hir().span(expr.hir_id), &msg); } } } @@ -120,8 +120,8 @@ fn build_suggestion<'tcx>( receiver_expr: &Expr<'_>, cast_lhs_expr: &Expr<'_>, ) -> Option { - let receiver = snippet_opt(cx, receiver_expr.span)?; - let cast_lhs = snippet_opt(cx, cast_lhs_expr.span)?; + let receiver = snippet_opt(cx, cx.tcx.hir().span(receiver_expr.hir_id))?; + let cast_lhs = snippet_opt(cx, cx.tcx.hir().span(cast_lhs_expr.hir_id))?; Some(format!("{}.{}({})", receiver, method.suggestion(), cast_lhs)) } diff --git a/src/tools/clippy/clippy_lints/src/question_mark.rs b/src/tools/clippy/clippy_lints/src/question_mark.rs index 6c480d48c7561..11a79229aabc1 100644 --- a/src/tools/clippy/clippy_lints/src/question_mark.rs +++ b/src/tools/clippy/clippy_lints/src/question_mark.rs @@ -83,7 +83,7 @@ impl QuestionMark { span_lint_and_sugg( cx, QUESTION_MARK, - expr.span, + cx.tcx.hir().span(expr.hir_id), "this block may be rewritten with the `?` operator", "replace it with", replacement_str, @@ -115,7 +115,7 @@ impl QuestionMark { if Self::expression_returns_none(cx, arms[1].body); then { let mut applicability = Applicability::MachineApplicable; - let receiver_str = snippet_with_applicability(cx, subject.span, "..", &mut applicability); + let receiver_str = snippet_with_applicability(cx, cx.tcx.hir().span(subject.hir_id), "..", &mut applicability); let replacement = format!( "{}{}?", receiver_str, @@ -125,7 +125,7 @@ impl QuestionMark { span_lint_and_sugg( cx, QUESTION_MARK, - expr.span, + cx.tcx.hir().span(expr.hir_id), "this if-let-else may be rewritten with the `?` operator", "replace it with", replacement, @@ -138,7 +138,7 @@ impl QuestionMark { fn moves_by_default(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool { let expr_ty = cx.typeck_results().expr_ty(expression); - !expr_ty.is_copy_modulo_regions(cx.tcx.at(expression.span), cx.param_env) + !expr_ty.is_copy_modulo_regions(cx.tcx.at(cx.tcx.hir().span(expression.hir_id)), cx.param_env) } fn is_option(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool { diff --git a/src/tools/clippy/clippy_lints/src/ranges.rs b/src/tools/clippy/clippy_lints/src/ranges.rs index 687fd78d857ea..cb91c48b17a7d 100644 --- a/src/tools/clippy/clippy_lints/src/ranges.rs +++ b/src/tools/clippy/clippy_lints/src/ranges.rs @@ -186,7 +186,7 @@ impl<'tcx> LateLintPass<'tcx> for Ranges { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { match expr.kind { ExprKind::MethodCall(ref path, _, ref args, _) => { - check_range_zip_with_len(cx, path, args, expr.span); + check_range_zip_with_len(cx, path, args, cx.tcx.hir().span(expr.hir_id)); }, ExprKind::Binary(ref op, ref l, ref r) => { if meets_msrv(self.msrv.as_ref(), &MANUAL_RANGE_CONTAINS_MSRV) { @@ -208,7 +208,7 @@ fn check_possible_range_contains(cx: &LateContext<'_>, op: BinOpKind, l: &Expr<' return; } - let span = expr.span; + let span = cx.tcx.hir().span(expr.hir_id); let combine_and = match op { BinOpKind::And | BinOpKind::BitAnd => true, BinOpKind::Or | BinOpKind::BitOr => false, @@ -299,11 +299,11 @@ fn check_range_bounds(cx: &LateContext<'_>, ex: &Expr<'_>) -> Option<(Constant, }; if let Some(id) = match_ident(l) { if let Some((c, _)) = constant(cx, cx.typeck_results(), r) { - return Some((c, id, l.span, r.span, ordering, inclusive)); + return Some((c, id, cx.tcx.hir().span(l.hir_id), cx.tcx.hir().span(r.hir_id), ordering, inclusive)); } } else if let Some(id) = match_ident(r) { if let Some((c, _)) = constant(cx, cx.typeck_results(), l) { - return Some((c, id, r.span, l.span, ordering.reverse(), inclusive)); + return Some((c, id, cx.tcx.hir().span(r.hir_id), cx.tcx.hir().span(l.hir_id), ordering.reverse(), inclusive)); } } } @@ -345,7 +345,7 @@ fn check_range_zip_with_len(cx: &LateContext<'_>, path: &PathSegment<'_>, args: RANGE_ZIP_WITH_LEN, span, &format!("it is more idiomatic to use `{}.iter().enumerate()`", - snippet(cx, iter_args[0].span, "_")) + snippet(cx, cx.tcx.hir().span(iter_args[0].hir_id), "_")) ); } } @@ -362,13 +362,13 @@ fn check_exclusive_range_plus_one(cx: &LateContext<'_>, expr: &Expr<'_>) { }) = higher::range(expr); if let Some(y) = y_plus_one(cx, end); then { - let span = if expr.span.from_expansion() { - expr.span + let span = if cx.tcx.hir().span(expr.hir_id).from_expansion() { + cx.tcx.hir().span(expr.hir_id) .ctxt() .outer_expn_data() .call_site } else { - expr.span + cx.tcx.hir().span(expr.hir_id) }; span_lint_and_then( cx, @@ -410,13 +410,13 @@ fn check_inclusive_range_minus_one(cx: &LateContext<'_>, expr: &Expr<'_>) { span_lint_and_then( cx, RANGE_MINUS_ONE, - expr.span, + cx.tcx.hir().span(expr.hir_id), "an exclusive range would be more readable", |diag| { let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string()); let end = Sugg::hir(cx, y, "y"); diag.span_suggestion( - expr.span, + cx.tcx.hir().span(expr.hir_id), "use", format!("{}..{}", start, end), Applicability::MachineApplicable, // snippet @@ -468,32 +468,34 @@ fn check_reversed_empty_range(cx: &LateContext<'_>, expr: &Expr<'_>) { then { if inside_indexing_expr(cx, expr) { // Avoid linting `N..N` as it has proven to be useful, see #5689 and #5628 ... + let expr_span = cx.tcx.hir().span(expr.hir_id); if ordering != Ordering::Equal { span_lint( cx, REVERSED_EMPTY_RANGES, - expr.span, + expr_span, "this range is reversed and using it to index a slice will panic at run-time", ); } // ... except in for loop arguments for backwards compatibility with `reverse_range_loop` } else if ordering != Ordering::Equal || is_for_loop_arg(cx, expr) { + let expr_span = cx.tcx.hir().span(expr.hir_id); span_lint_and_then( cx, REVERSED_EMPTY_RANGES, - expr.span, + expr_span, "this range is empty so it will yield no values", |diag| { if ordering != Ordering::Equal { - let start_snippet = snippet(cx, start.span, "_"); - let end_snippet = snippet(cx, end.span, "_"); + let start_snippet = snippet(cx, cx.tcx.hir().span(start.hir_id), "_"); + let end_snippet = snippet(cx, cx.tcx.hir().span(end.hir_id), "_"); let dots = match limits { RangeLimits::HalfOpen => "..", RangeLimits::Closed => "..=" }; diag.span_suggestion( - expr.span, + expr_span, "consider using the following if you are attempting to iterate over this \ range in reverse", format!("({}{}{}).rev()", end_snippet, dots, start_snippet), diff --git a/src/tools/clippy/clippy_lints/src/redundant_closure_call.rs b/src/tools/clippy/clippy_lints/src/redundant_closure_call.rs index f398b3fff25a3..db4d7011b1a6e 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_closure_call.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_closure_call.rs @@ -146,7 +146,7 @@ impl<'tcx> LateLintPass<'tcx> for RedundantClosureCall { span_lint( cx, REDUNDANT_CLOSURE_CALL, - second.span, + cx.tcx.hir().span(second.hir_id), "closure called just once immediately after it was declared", ); } diff --git a/src/tools/clippy/clippy_lints/src/redundant_slicing.rs b/src/tools/clippy/clippy_lints/src/redundant_slicing.rs index e5ced13514f79..e6657e2bd639d 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_slicing.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_slicing.rs @@ -39,7 +39,7 @@ declare_lint_pass!(RedundantSlicing => [REDUNDANT_SLICING]); impl LateLintPass<'_> for RedundantSlicing { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), cx.tcx.hir().span(expr.hir_id)) { return; } @@ -50,12 +50,12 @@ impl LateLintPass<'_> for RedundantSlicing { if TyS::same_type(cx.typeck_results().expr_ty(expr), cx.typeck_results().expr_ty(indexed)); then { let mut app = Applicability::MachineApplicable; - let hint = snippet_with_applicability(cx, indexed.span, "..", &mut app).into_owned(); + let hint = snippet_with_applicability(cx, cx.tcx.hir().span(indexed.hir_id), "..", &mut app).into_owned(); span_lint_and_sugg( cx, REDUNDANT_SLICING, - expr.span, + cx.tcx.hir().span(expr.hir_id), "redundant slicing of the whole range", "use the original slice instead", hint, diff --git a/src/tools/clippy/clippy_lints/src/regex.rs b/src/tools/clippy/clippy_lints/src/regex.rs index 1edea61314893..af783d886c869 100644 --- a/src/tools/clippy/clippy_lints/src/regex.rs +++ b/src/tools/clippy/clippy_lints/src/regex.rs @@ -156,14 +156,14 @@ fn check_regex<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, utf8: bool) { match parser.parse(r) { Ok(r) => { if let Some(repl) = is_trivial_regex(&r) { - span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl); + span_lint_and_help(cx, TRIVIAL_REGEX, cx.tcx.hir().span(expr.hir_id), "trivial regex", None, repl); } }, Err(regex_syntax::Error::Parse(e)) => { span_lint( cx, INVALID_REGEX, - str_span(expr.span, *e.span(), offset), + str_span(cx.tcx.hir().span(expr.hir_id), *e.span(), offset), &format!("regex syntax error: {}", e.kind()), ); }, @@ -171,12 +171,12 @@ fn check_regex<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, utf8: bool) { span_lint( cx, INVALID_REGEX, - str_span(expr.span, *e.span(), offset), + str_span(cx.tcx.hir().span(expr.hir_id), *e.span(), offset), &format!("regex syntax error: {}", e.kind()), ); }, Err(e) => { - span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e)); + span_lint(cx, INVALID_REGEX, cx.tcx.hir().span(expr.hir_id), &format!("regex syntax error: {}", e)); }, } } @@ -184,14 +184,14 @@ fn check_regex<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, utf8: bool) { match parser.parse(&r) { Ok(r) => { if let Some(repl) = is_trivial_regex(&r) { - span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl); + span_lint_and_help(cx, TRIVIAL_REGEX, cx.tcx.hir().span(expr.hir_id), "trivial regex", None, repl); } }, Err(regex_syntax::Error::Parse(e)) => { span_lint( cx, INVALID_REGEX, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()), ); }, @@ -199,12 +199,12 @@ fn check_regex<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, utf8: bool) { span_lint( cx, INVALID_REGEX, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()), ); }, Err(e) => { - span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e)); + span_lint(cx, INVALID_REGEX, cx.tcx.hir().span(expr.hir_id), &format!("regex syntax error: {}", e)); }, } } diff --git a/src/tools/clippy/clippy_lints/src/repeat_once.rs b/src/tools/clippy/clippy_lints/src/repeat_once.rs index d34e744eb944c..4387f713afd99 100644 --- a/src/tools/clippy/clippy_lints/src/repeat_once.rs +++ b/src/tools/clippy/clippy_lints/src/repeat_once.rs @@ -43,37 +43,39 @@ impl<'tcx> LateLintPass<'tcx> for RepeatOnce { if let ExprKind::MethodCall(path, _, [receiver, count], _) = &expr.kind; if path.ident.name == sym!(repeat); if let Some(Constant::Int(1)) = constant_context(cx, cx.typeck_results()).expr(&count); - if !in_macro(receiver.span); + let receiver_span = cx.tcx.hir().span(receiver.hir_id); + if !in_macro(receiver_span); then { let ty = cx.typeck_results().expr_ty(&receiver).peel_refs(); + let expr_span = cx.tcx.hir().span(expr.hir_id); if ty.is_str() { span_lint_and_sugg( cx, REPEAT_ONCE, - expr.span, + expr_span, "calling `repeat(1)` on str", "consider using `.to_string()` instead", - format!("{}.to_string()", snippet(cx, receiver.span, r#""...""#)), + format!("{}.to_string()", snippet(cx, receiver_span, r#""...""#)), Applicability::MachineApplicable, ); } else if ty.builtin_index().is_some() { span_lint_and_sugg( cx, REPEAT_ONCE, - expr.span, + expr_span, "calling `repeat(1)` on slice", "consider using `.to_vec()` instead", - format!("{}.to_vec()", snippet(cx, receiver.span, r#""...""#)), + format!("{}.to_vec()", snippet(cx, receiver_span, r#""...""#)), Applicability::MachineApplicable, ); } else if is_type_diagnostic_item(cx, ty, sym::string_type) { span_lint_and_sugg( cx, REPEAT_ONCE, - expr.span, + expr_span, "calling `repeat(1)` on a string literal", "consider using `.clone()` instead", - format!("{}.clone()", snippet(cx, receiver.span, r#""...""#)), + format!("{}.clone()", snippet(cx, receiver_span, r#""...""#)), Applicability::MachineApplicable, ); } diff --git a/src/tools/clippy/clippy_lints/src/returns.rs b/src/tools/clippy/clippy_lints/src/returns.rs index fed2e494138fd..c8a956f3184dc 100644 --- a/src/tools/clippy/clippy_lints/src/returns.rs +++ b/src/tools/clippy/clippy_lints/src/returns.rs @@ -87,8 +87,10 @@ impl<'tcx> LateLintPass<'tcx> for Return { if let ExprKind::Path(qpath) = &retexpr.kind; if match_qpath(qpath, &[&*ident.name.as_str()]); if !last_statement_borrows(cx, initexpr); - if !in_external_macro(cx.sess(), initexpr.span); - if !in_external_macro(cx.sess(), retexpr.span); + let initexpr_span = cx.tcx.hir().span(initexpr.hir_id); + if !in_external_macro(cx.sess(), initexpr_span); + let retexpr_span = cx.tcx.hir().span(retexpr.hir_id); + if !in_external_macro(cx.sess(), retexpr_span); let local_span = cx.tcx.hir().span(local.hir_id); if !in_external_macro(cx.sess(), local_span); if !in_macro(local_span); @@ -96,12 +98,12 @@ impl<'tcx> LateLintPass<'tcx> for Return { span_lint_and_then( cx, LET_AND_RETURN, - retexpr.span, + retexpr_span, "returning the result of a `let` binding from a block", |err| { err.span_label(local_span, "unnecessary `let` binding"); - if let Some(mut snippet) = snippet_opt(cx, initexpr.span) { + if let Some(mut snippet) = snippet_opt(cx, initexpr_span) { if !cx.typeck_results().expr_adjustments(&retexpr).is_empty() { snippet.push_str(" as _"); } @@ -109,12 +111,12 @@ impl<'tcx> LateLintPass<'tcx> for Return { "return the expression directly", vec![ (local_span, String::new()), - (retexpr.span, snippet), + (retexpr_span, snippet), ], Applicability::MachineApplicable, ); } else { - err.span_help(initexpr.span, "this expression can be directly returned"); + err.span_help(initexpr_span, "this expression can be directly returned"); } }, ); @@ -139,7 +141,7 @@ impl<'tcx> LateLintPass<'tcx> for Return { } else { RetReplacement::Empty }; - check_final_expr(cx, &body.value, Some(body.value.span), replacement) + check_final_expr(cx, &body.value, Some(cx.tcx.hir().span(body.value.hir_id)), replacement) }, FnKind::ItemFn(..) | FnKind::Method(..) => { if let ExprKind::Block(ref block, _) = body.value.kind { @@ -156,7 +158,7 @@ fn attr_is_cfg(attr: &Attribute) -> bool { fn check_block_return<'tcx>(cx: &LateContext<'tcx>, block: &Block<'tcx>) { if let Some(expr) = block.expr { - check_final_expr(cx, expr, Some(expr.span), RetReplacement::Empty); + check_final_expr(cx, expr, Some(cx.tcx.hir().span(expr.hir_id)), RetReplacement::Empty); } else if let Some(stmt) = block.stmts.iter().last() { match stmt.kind { StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => { @@ -185,7 +187,7 @@ fn check_final_expr<'tcx>( emit_return_lint( cx, span.expect("`else return` is not possible"), - inner.as_ref().map(|i| i.span), + inner.as_ref().map(|i| cx.tcx.hir().span(i.hir_id)), replacement, ); } @@ -210,7 +212,12 @@ fn check_final_expr<'tcx>( ExprKind::Match(_, ref arms, source) => match source { MatchSource::Normal => { for arm in arms.iter() { - check_final_expr(cx, &arm.body, Some(arm.body.span), RetReplacement::Block); + check_final_expr( + cx, + &arm.body, + Some(cx.tcx.hir().span(arm.body.hir_id)), + RetReplacement::Block, + ); } }, MatchSource::IfLetDesugar { diff --git a/src/tools/clippy/clippy_lints/src/self_assignment.rs b/src/tools/clippy/clippy_lints/src/self_assignment.rs index e096c9aebc122..85368a839ff50 100644 --- a/src/tools/clippy/clippy_lints/src/self_assignment.rs +++ b/src/tools/clippy/clippy_lints/src/self_assignment.rs @@ -37,12 +37,12 @@ impl<'tcx> LateLintPass<'tcx> for SelfAssignment { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if let ExprKind::Assign(lhs, rhs, _) = &expr.kind { if eq_expr_value(cx, lhs, rhs) { - let lhs = snippet(cx, lhs.span, ""); - let rhs = snippet(cx, rhs.span, ""); + let lhs = snippet(cx, cx.tcx.hir().span(lhs.hir_id), ""); + let rhs = snippet(cx, cx.tcx.hir().span(rhs.hir_id), ""); span_lint( cx, SELF_ASSIGNMENT, - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!("self-assignment of `{}` to `{}`", rhs, lhs), ); } diff --git a/src/tools/clippy/clippy_lints/src/semicolon_if_nothing_returned.rs b/src/tools/clippy/clippy_lints/src/semicolon_if_nothing_returned.rs index 8bc9272691087..d823872704edc 100644 --- a/src/tools/clippy/clippy_lints/src/semicolon_if_nothing_returned.rs +++ b/src/tools/clippy/clippy_lints/src/semicolon_if_nothing_returned.rs @@ -41,7 +41,7 @@ impl LateLintPass<'_> for SemicolonIfNothingReturned { if let Some(expr) = block.expr; let t_expr = cx.typeck_results().expr_ty(expr); if t_expr.is_unit(); - if let snippet = snippet_with_macro_callsite(cx, expr.span, "}"); + if let snippet = snippet_with_macro_callsite(cx, cx.tcx.hir().span(expr.hir_id), "}"); if !snippet.ends_with('}'); then { // filter out the desugared `for` loop @@ -54,7 +54,7 @@ impl LateLintPass<'_> for SemicolonIfNothingReturned { span_lint_and_sugg( cx, SEMICOLON_IF_NOTHING_RETURNED, - expr.span.source_callsite(), + cx.tcx.hir().span(expr.hir_id).source_callsite(), "consider adding a `;` to the last statement for consistent formatting", "add a `;` here", suggestion, diff --git a/src/tools/clippy/clippy_lints/src/shadow.rs b/src/tools/clippy/clippy_lints/src/shadow.rs index cba8fe429854e..866d93802e39e 100644 --- a/src/tools/clippy/clippy_lints/src/shadow.rs +++ b/src/tools/clippy/clippy_lints/src/shadow.rs @@ -106,7 +106,7 @@ impl<'tcx> LateLintPass<'tcx> for Shadow { body: &'tcx Body<'_>, _: HirId, ) { - if in_external_macro(cx.sess(), body.value.span) { + if in_external_macro(cx.sess(), cx.tcx.hir().span(body.value.hir_id)) { return; } check_fn(cx, decl, body); @@ -261,6 +261,7 @@ fn lint_shadow<'tcx>( prev_span: Span, ) { if let Some(expr) = init { + let expr_span = cx.tcx.hir().span(expr.hir_id); if is_self_shadow(name, expr) { span_lint_and_then( cx, @@ -269,7 +270,7 @@ fn lint_shadow<'tcx>( &format!( "`{}` is shadowed by itself in `{}`", snippet(cx, pattern_span, "_"), - snippet(cx, expr.span, "..") + snippet(cx, expr_span, "..") ), |diag| { diag.span_note(prev_span, "previous binding is here"); @@ -283,10 +284,10 @@ fn lint_shadow<'tcx>( &format!( "`{}` is shadowed by `{}` which reuses the original value", snippet(cx, pattern_span, "_"), - snippet(cx, expr.span, "..") + snippet(cx, expr_span, "..") ), |diag| { - diag.span_note(expr.span, "initialization happens here"); + diag.span_note(expr_span, "initialization happens here"); diag.span_note(prev_span, "previous binding is here"); }, ); @@ -295,9 +296,12 @@ fn lint_shadow<'tcx>( cx, SHADOW_UNRELATED, pattern_span, - &format!("`{}` is being shadowed", snippet(cx, pattern_span, "_")), + &format!( + "`{}` is being shadowed", + snippet(cx, pattern_span, "_"), + ), |diag| { - diag.span_note(expr.span, "initialization happens here"); + diag.span_note(expr_span, "initialization happens here"); diag.span_note(prev_span, "previous binding is here"); }, ); @@ -316,7 +320,7 @@ fn lint_shadow<'tcx>( } fn check_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, bindings: &mut Vec<(Symbol, Span)>) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), cx.tcx.hir().span(expr.hir_id)) { return; } match expr.kind { diff --git a/src/tools/clippy/clippy_lints/src/size_of_in_element_count.rs b/src/tools/clippy/clippy_lints/src/size_of_in_element_count.rs index 87e386baadc54..6f9b72e8ac393 100644 --- a/src/tools/clippy/clippy_lints/src/size_of_in_element_count.rs +++ b/src/tools/clippy/clippy_lints/src/size_of_in_element_count.rs @@ -138,7 +138,7 @@ impl<'tcx> LateLintPass<'tcx> for SizeOfInElementCount { span_lint_and_help( cx, SIZE_OF_IN_ELEMENT_COUNT, - count_expr.span, + cx.tcx.hir().span(count_expr.hir_id), LINT_MSG, None, HELP_MSG diff --git a/src/tools/clippy/clippy_lints/src/slow_vector_initialization.rs b/src/tools/clippy/clippy_lints/src/slow_vector_initialization.rs index 96f6881556cf3..fb69dc422c8f7 100644 --- a/src/tools/clippy/clippy_lints/src/slow_vector_initialization.rs +++ b/src/tools/clippy/clippy_lints/src/slow_vector_initialization.rs @@ -176,9 +176,9 @@ impl SlowVectorInit { ) { let len_expr = Sugg::hir(cx, vec_alloc.len_expr, "len"); - span_lint_and_then(cx, lint, slow_fill.span, msg, |diag| { + span_lint_and_then(cx, lint, cx.tcx.hir().span(slow_fill.hir_id), msg, |diag| { diag.span_suggestion( - vec_alloc.allocation_expr.span, + cx.tcx.hir().span(vec_alloc.allocation_expr.hir_id), "consider replace allocation with", format!("vec![0; {}]", len_expr), Applicability::Unspecified, diff --git a/src/tools/clippy/clippy_lints/src/stable_sort_primitive.rs b/src/tools/clippy/clippy_lints/src/stable_sort_primitive.rs index 276a9338819d9..bfa8af909ad1d 100644 --- a/src/tools/clippy/clippy_lints/src/stable_sort_primitive.rs +++ b/src/tools/clippy/clippy_lints/src/stable_sort_primitive.rs @@ -110,7 +110,7 @@ impl LateLintPass<'_> for StableSortPrimitive { span_lint_and_then( cx, STABLE_SORT_PRIMITIVE, - expr.span, + cx.tcx.hir().span(expr.hir_id), format!( "used `{}` on primitive type `{}`", detection.method.stable_name(), @@ -119,7 +119,7 @@ impl LateLintPass<'_> for StableSortPrimitive { .as_str(), |diag| { diag.span_suggestion( - expr.span, + cx.tcx.hir().span(expr.hir_id), "try", format!( "{}.{}({})", diff --git a/src/tools/clippy/clippy_lints/src/strings.rs b/src/tools/clippy/clippy_lints/src/strings.rs index 31dd5965473d3..0b11150c731a7 100644 --- a/src/tools/clippy/clippy_lints/src/strings.rs +++ b/src/tools/clippy/clippy_lints/src/strings.rs @@ -113,7 +113,7 @@ declare_lint_pass!(StringAdd => [STRING_ADD, STRING_ADD_ASSIGN]); impl<'tcx> LateLintPass<'tcx> for StringAdd { fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { - if in_external_macro(cx.sess(), e.span) { + if in_external_macro(cx.sess(), cx.tcx.hir().span(e.hir_id)) { return; } @@ -140,7 +140,7 @@ impl<'tcx> LateLintPass<'tcx> for StringAdd { span_lint( cx, STRING_ADD, - e.span, + cx.tcx.hir().span(e.hir_id), "you added something to a string. Consider using `String::push_str()` instead", ); } @@ -149,7 +149,7 @@ impl<'tcx> LateLintPass<'tcx> for StringAdd { span_lint( cx, STRING_ADD_ASSIGN, - e.span, + cx.tcx.hir().span(e.hir_id), "you assigned the result of adding something to this string. Consider using \ `String::push_str()` instead", ); @@ -215,7 +215,7 @@ impl<'tcx> LateLintPass<'tcx> for StringLitAsBytes { // Find string::as_bytes if let ExprKind::AddrOf(BorrowKind::Ref, _, ref args) = args[0].kind; if let ExprKind::Index(ref left, ref right) = args.kind; - let (method_names, expressions, _) = method_calls(left, 1); + let (method_names, expressions, _) = method_calls(cx, left, 1); if method_names.len() == 1; if expressions.len() == 1; if expressions[0].len() == 1; @@ -230,17 +230,17 @@ impl<'tcx> LateLintPass<'tcx> for StringLitAsBytes { let snippet_app = snippet_with_applicability( cx, - string_expression.span, "..", + cx.tcx.hir().span(string_expression.hir_id), "..", &mut applicability, ); span_lint_and_sugg( cx, STRING_FROM_UTF8_AS_BYTES, - e.span, + cx.tcx.hir().span(e.hir_id), "calling a slice of `as_bytes()` with `from_utf8` should be not necessary", "try", - format!("Some(&{}[{}])", snippet_app, snippet(cx, right.span, "..")), + format!("Some(&{}[{}])", snippet_app, snippet(cx, cx.tcx.hir().span(right.hir_id), "..")), applicability ) } @@ -252,16 +252,16 @@ impl<'tcx> LateLintPass<'tcx> for StringLitAsBytes { if let ExprKind::Lit(lit) = &args[0].kind; if let LitKind::Str(lit_content, _) = &lit.node; then { - let callsite = snippet(cx, args[0].span.source_callsite(), r#""foo""#); + let callsite = snippet(cx, cx.tcx.hir().span(args[0].hir_id).source_callsite(), r#""foo""#); let mut applicability = Applicability::MachineApplicable; if callsite.starts_with("include_str!") { span_lint_and_sugg( cx, STRING_LIT_AS_BYTES, - e.span, + cx.tcx.hir().span(e.hir_id), "calling `as_bytes()` on `include_str!(..)`", "consider using `include_bytes!(..)` instead", - snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability).replacen( + snippet_with_applicability(cx, cx.tcx.hir().span(args[0].hir_id), r#""foo""#, &mut applicability).replacen( "include_str", "include_bytes", 1, @@ -270,17 +270,17 @@ impl<'tcx> LateLintPass<'tcx> for StringLitAsBytes { ); } else if lit_content.as_str().is_ascii() && lit_content.as_str().len() <= MAX_LENGTH_BYTE_STRING_LIT - && !args[0].span.from_expansion() + && !cx.tcx.hir().span(args[0].hir_id).from_expansion() { span_lint_and_sugg( cx, STRING_LIT_AS_BYTES, - e.span, + cx.tcx.hir().span(e.hir_id), "calling `as_bytes()` on a string literal", "consider using a byte string literal instead", format!( "b{}", - snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability) + snippet_with_applicability(cx, cx.tcx.hir().span(args[0].hir_id), r#""foo""#, &mut applicability) ), applicability, ); @@ -329,7 +329,7 @@ impl LateLintPass<'_> for StrToString { span_lint_and_help( cx, STR_TO_STRING, - expr.span, + cx.tcx.hir().span(expr.hir_id), "`to_string()` called on a `&str`", None, "consider using `.to_owned()`", @@ -377,7 +377,7 @@ impl LateLintPass<'_> for StringToString { span_lint_and_help( cx, STRING_TO_STRING, - expr.span, + cx.tcx.hir().span(expr.hir_id), "`to_string()` called on a `String`", None, "consider using `.clone()`", diff --git a/src/tools/clippy/clippy_lints/src/swap.rs b/src/tools/clippy/clippy_lints/src/swap.rs index c91640a2c807d..181179fd05a1f 100644 --- a/src/tools/clippy/clippy_lints/src/swap.rs +++ b/src/tools/clippy/clippy_lints/src/swap.rs @@ -116,8 +116,8 @@ fn check_manual_swap(cx: &LateContext<'_>, block: &Block<'_>) { format!( "{}.swap({}, {})", slice.maybe_par(), - snippet_with_applicability(cx, idx1.span, "..", &mut applicability), - snippet_with_applicability(cx, idx2.span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(idx1.hir_id), "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(idx2.hir_id), "..", &mut applicability), ), ) } else { @@ -133,7 +133,7 @@ fn check_manual_swap(cx: &LateContext<'_>, block: &Block<'_>) { (true, String::new(), String::new()) }; - let span = cx.tcx.hir().span(w[0].hir_id).to(second.span); + let span = cx.tcx.hir().span(w[0].hir_id).to(cx.tcx.hir().span(second.hir_id)); span_lint_and_then( cx, @@ -218,7 +218,7 @@ fn check_suspicious_swap(cx: &LateContext<'_>, block: &Block<'_>) { if_chain! { if let StmtKind::Semi(ref first) = w[0].kind; if let StmtKind::Semi(ref second) = w[1].kind; - if !differing_macro_contexts(first.span, second.span); + if !differing_macro_contexts(cx.tcx.hir().span(first.hir_id), cx.tcx.hir().span(second.hir_id)); if let ExprKind::Assign(ref lhs0, ref rhs0, _) = first.kind; if let ExprKind::Assign(ref lhs1, ref rhs1, _) = second.kind; if eq_expr_value(cx, lhs0, rhs1); @@ -236,7 +236,7 @@ fn check_suspicious_swap(cx: &LateContext<'_>, block: &Block<'_>) { (String::new(), String::new(), String::new()) }; - let span = first.span.to(second.span); + let span = cx.tcx.hir().span(first.hir_id).to(cx.tcx.hir().span(second.hir_id)); span_lint_and_then(cx, ALMOST_SWAPPED, diff --git a/src/tools/clippy/clippy_lints/src/temporary_assignment.rs b/src/tools/clippy/clippy_lints/src/temporary_assignment.rs index fb891866364cc..7ac88852d1f94 100644 --- a/src/tools/clippy/clippy_lints/src/temporary_assignment.rs +++ b/src/tools/clippy/clippy_lints/src/temporary_assignment.rs @@ -35,7 +35,7 @@ impl<'tcx> LateLintPass<'tcx> for TemporaryAssignment { base = f; } if is_temporary(base) && !is_adjusted(cx, base) { - span_lint(cx, TEMPORARY_ASSIGNMENT, expr.span, "assignment to temporary"); + span_lint(cx, TEMPORARY_ASSIGNMENT, cx.tcx.hir().span(expr.hir_id), "assignment to temporary"); } } } diff --git a/src/tools/clippy/clippy_lints/src/to_digit_is_some.rs b/src/tools/clippy/clippy_lints/src/to_digit_is_some.rs index eeda39bfa2087..b22c6363a0c5e 100644 --- a/src/tools/clippy/clippy_lints/src/to_digit_is_some.rs +++ b/src/tools/clippy/clippy_lints/src/to_digit_is_some.rs @@ -71,13 +71,13 @@ impl<'tcx> LateLintPass<'tcx> for ToDigitIsSome { if let Some((is_method_call, char_arg, radix_arg)) = match_result { let mut applicability = Applicability::MachineApplicable; - let char_arg_snip = snippet_with_applicability(cx, char_arg.span, "_", &mut applicability); - let radix_snip = snippet_with_applicability(cx, radix_arg.span, "_", &mut applicability); + let char_arg_snip = snippet_with_applicability(cx, cx.tcx.hir().span(char_arg.hir_id), "_", &mut applicability); + let radix_snip = snippet_with_applicability(cx, cx.tcx.hir().span(radix_arg.hir_id), "_", &mut applicability); span_lint_and_sugg( cx, TO_DIGIT_IS_SOME, - expr.span, + cx.tcx.hir().span(expr.hir_id), "use of `.to_digit(..).is_some()`", "try this", if is_method_call { diff --git a/src/tools/clippy/clippy_lints/src/to_string_in_display.rs b/src/tools/clippy/clippy_lints/src/to_string_in_display.rs index 84ec2aa18abcc..5948c25a88c15 100644 --- a/src/tools/clippy/clippy_lints/src/to_string_in_display.rs +++ b/src/tools/clippy/clippy_lints/src/to_string_in_display.rs @@ -100,7 +100,7 @@ impl LateLintPass<'_> for ToStringInDisplay { span_lint( cx, TO_STRING_IN_DISPLAY, - expr.span, + cx.tcx.hir().span(expr.hir_id), "using `to_string` in `fmt::Display` implementation might lead to infinite recursion", ); } diff --git a/src/tools/clippy/clippy_lints/src/transmute/crosspointer_transmute.rs b/src/tools/clippy/clippy_lints/src/transmute/crosspointer_transmute.rs index ce87defaa9406..41010478cbde9 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/crosspointer_transmute.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/crosspointer_transmute.rs @@ -12,7 +12,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty span_lint( cx, CROSSPOINTER_TRANSMUTE, - e.span, + cx.tcx.hir().span(e.hir_id), &format!( "transmute from a type (`{}`) to the type that it points to (`{}`)", from_ty, to_ty @@ -24,7 +24,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty span_lint( cx, CROSSPOINTER_TRANSMUTE, - e.span, + cx.tcx.hir().span(e.hir_id), &format!( "transmute from a type (`{}`) to a pointer to that type (`{}`)", from_ty, to_ty diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmute_float_to_int.rs b/src/tools/clippy/clippy_lints/src/transmute/transmute_float_to_int.rs index 562d880e39afb..8a132cea155d1 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmute_float_to_int.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmute_float_to_int.rs @@ -22,7 +22,7 @@ pub(super) fn check<'tcx>( span_lint_and_then( cx, TRANSMUTE_FLOAT_TO_INT, - e.span, + cx.tcx.hir().span(e.hir_id), &format!("transmute from a `{}` to a `{}`", from_ty, to_ty), |diag| { let mut expr = &args[0]; @@ -55,7 +55,12 @@ pub(super) fn check<'tcx>( arg }; - diag.span_suggestion(e.span, "consider using", arg.to_string(), Applicability::Unspecified); + diag.span_suggestion( + cx.tcx.hir().span(e.hir_id), + "consider using", + arg.to_string(), + Applicability::Unspecified, + ); }, ); true diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmute_int_to_bool.rs b/src/tools/clippy/clippy_lints/src/transmute/transmute_int_to_bool.rs index 5b609f906a3d7..f1302ad1642cc 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmute_int_to_bool.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmute_int_to_bool.rs @@ -21,13 +21,13 @@ pub(super) fn check<'tcx>( span_lint_and_then( cx, TRANSMUTE_INT_TO_BOOL, - e.span, + cx.tcx.hir().span(e.hir_id), &format!("transmute from a `{}` to a `bool`", from_ty), |diag| { let arg = sugg::Sugg::hir(cx, &args[0], ".."); let zero = sugg::Sugg::NonParen(Cow::from("0")); diag.span_suggestion( - e.span, + cx.tcx.hir().span(e.hir_id), "consider using", sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(), Applicability::Unspecified, diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmute_int_to_char.rs b/src/tools/clippy/clippy_lints/src/transmute/transmute_int_to_char.rs index 29d2450618a7e..7291bc6a7005c 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmute_int_to_char.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmute_int_to_char.rs @@ -20,7 +20,7 @@ pub(super) fn check<'tcx>( span_lint_and_then( cx, TRANSMUTE_INT_TO_CHAR, - e.span, + cx.tcx.hir().span(e.hir_id), &format!("transmute from a `{}` to a `char`", from_ty), |diag| { let arg = sugg::Sugg::hir(cx, &args[0], ".."); @@ -30,7 +30,7 @@ pub(super) fn check<'tcx>( arg }; diag.span_suggestion( - e.span, + cx.tcx.hir().span(e.hir_id), "consider using", format!("std::char::from_u32({}).unwrap()", arg.to_string()), Applicability::Unspecified, diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmute_int_to_float.rs b/src/tools/clippy/clippy_lints/src/transmute/transmute_int_to_float.rs index f83fba8966a11..13f2d9350abbd 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmute_int_to_float.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmute_int_to_float.rs @@ -20,7 +20,7 @@ pub(super) fn check<'tcx>( span_lint_and_then( cx, TRANSMUTE_INT_TO_FLOAT, - e.span, + cx.tcx.hir().span(e.hir_id), &format!("transmute from a `{}` to a `{}`", from_ty, to_ty), |diag| { let arg = sugg::Sugg::hir(cx, &args[0], ".."); @@ -33,7 +33,7 @@ pub(super) fn check<'tcx>( arg }; diag.span_suggestion( - e.span, + cx.tcx.hir().span(e.hir_id), "consider using", format!("{}::from_bits({})", to_ty, arg.to_string()), Applicability::Unspecified, diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ptr.rs b/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ptr.rs index f4e60a3020cf5..19b6d26c38439 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ptr.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ptr.rs @@ -19,12 +19,17 @@ pub(super) fn check<'tcx>( span_lint_and_then( cx, TRANSMUTE_PTR_TO_PTR, - e.span, + cx.tcx.hir().span(e.hir_id), "transmute from a pointer to a pointer", |diag| { if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) { let sugg = arg.as_ty(cx.tcx.mk_ptr(*to_ty)); - diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified); + diag.span_suggestion( + cx.tcx.hir().span(e.hir_id), + "try", + sugg.to_string(), + Applicability::Unspecified, + ); } }, ); diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ref.rs b/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ref.rs index f5dbbbe33bc64..2d209e9d74430 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ref.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ref.rs @@ -21,7 +21,7 @@ pub(super) fn check<'tcx>( span_lint_and_then( cx, TRANSMUTE_PTR_TO_REF, - e.span, + cx.tcx.hir().span(e.hir_id), &format!( "transmute from a pointer type (`{}`) to a reference type (`{}`)", from_ty, to_ty @@ -41,7 +41,7 @@ pub(super) fn check<'tcx>( }; diag.span_suggestion( - e.span, + cx.tcx.hir().span(e.hir_id), "try", sugg::make_unop(deref, arg).to_string(), Applicability::Unspecified, diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmute_ref_to_ref.rs b/src/tools/clippy/clippy_lints/src/transmute/transmute_ref_to_ref.rs index 01b00bb0a2229..d12822fdc9f12 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmute_ref_to_ref.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmute_ref_to_ref.rs @@ -33,13 +33,13 @@ pub(super) fn check<'tcx>( span_lint_and_sugg( cx, TRANSMUTE_BYTES_TO_STR, - e.span, + cx.tcx.hir().span(e.hir_id), &format!("transmute from a `{}` to a `{}`", from_ty, to_ty), "consider using", format!( "std::str::from_utf8{}({}).unwrap()", postfix, - snippet(cx, args[0].span, ".."), + snippet(cx, cx.tcx.hir().span(args[0].hir_id), ".."), ), Applicability::Unspecified, ); @@ -50,7 +50,7 @@ pub(super) fn check<'tcx>( span_lint_and_then( cx, TRANSMUTE_PTR_TO_PTR, - e.span, + cx.tcx.hir().span(e.hir_id), "transmute from a reference to a reference", |diag| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) { let ty_from_and_mut = ty::TypeAndMut { @@ -67,7 +67,7 @@ pub(super) fn check<'tcx>( sugg_paren.addr_deref() }; diag.span_suggestion( - e.span, + cx.tcx.hir().span(e.hir_id), "try", sugg.to_string(), Applicability::Unspecified, diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmutes_expressible_as_ptr_casts.rs b/src/tools/clippy/clippy_lints/src/transmute/transmutes_expressible_as_ptr_casts.rs index dea896622f11c..e12b41bb44822 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmutes_expressible_as_ptr_casts.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmutes_expressible_as_ptr_casts.rs @@ -19,7 +19,7 @@ pub(super) fn check<'tcx>( span_lint_and_then( cx, TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS, - e.span, + cx.tcx.hir().span(e.hir_id), &format!( "transmute from `{}` to `{}` which could be expressed as a pointer cast instead", from_ty, to_ty @@ -27,7 +27,12 @@ pub(super) fn check<'tcx>( |diag| { if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) { let sugg = arg.as_ty(&to_ty.to_string()).to_string(); - diag.span_suggestion(e.span, "try", sugg, Applicability::MachineApplicable); + diag.span_suggestion( + cx.tcx.hir().span(e.hir_id), + "try", + sugg, + Applicability::MachineApplicable, + ); } }, ); diff --git a/src/tools/clippy/clippy_lints/src/transmute/unsound_collection_transmute.rs b/src/tools/clippy/clippy_lints/src/transmute/unsound_collection_transmute.rs index 503c5e0ff3822..0f93085c5c58e 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/unsound_collection_transmute.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/unsound_collection_transmute.rs @@ -32,7 +32,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty span_lint( cx, UNSOUND_COLLECTION_TRANSMUTE, - e.span, + cx.tcx.hir().span(e.hir_id), &format!( "transmute from `{}` to `{}` with mismatched layout is unsound", from_ty, to_ty diff --git a/src/tools/clippy/clippy_lints/src/transmute/useless_transmute.rs b/src/tools/clippy/clippy_lints/src/transmute/useless_transmute.rs index 83441514af051..5931f48692b2e 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/useless_transmute.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/useless_transmute.rs @@ -19,7 +19,7 @@ pub(super) fn check<'tcx>( span_lint( cx, USELESS_TRANSMUTE, - e.span, + cx.tcx.hir().span(e.hir_id), &format!("transmute from a type (`{}`) to itself", from_ty), ); true @@ -28,7 +28,7 @@ pub(super) fn check<'tcx>( span_lint_and_then( cx, USELESS_TRANSMUTE, - e.span, + cx.tcx.hir().span(e.hir_id), "transmute from a reference to a pointer", |diag| { if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) { @@ -43,7 +43,12 @@ pub(super) fn check<'tcx>( arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty) }; - diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified); + diag.span_suggestion( + cx.tcx.hir().span(e.hir_id), + "try", + sugg.to_string(), + Applicability::Unspecified, + ); } }, ); @@ -53,12 +58,12 @@ pub(super) fn check<'tcx>( span_lint_and_then( cx, USELESS_TRANSMUTE, - e.span, + cx.tcx.hir().span(e.hir_id), "transmute from an integer to a pointer", |diag| { if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) { diag.span_suggestion( - e.span, + cx.tcx.hir().span(e.hir_id), "try", arg.as_ty(&to_ty.to_string()).to_string(), Applicability::Unspecified, diff --git a/src/tools/clippy/clippy_lints/src/transmute/wrong_transmute.rs b/src/tools/clippy/clippy_lints/src/transmute/wrong_transmute.rs index d6d77f2c83456..788d7bcb821d7 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/wrong_transmute.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/wrong_transmute.rs @@ -12,7 +12,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty span_lint( cx, WRONG_TRANSMUTE, - e.span, + cx.tcx.hir().span(e.hir_id), &format!("transmute from a `{}` to a pointer", from_ty), ); true diff --git a/src/tools/clippy/clippy_lints/src/transmuting_null.rs b/src/tools/clippy/clippy_lints/src/transmuting_null.rs index 2ba2b646f004f..df1e439f578dc 100644 --- a/src/tools/clippy/clippy_lints/src/transmuting_null.rs +++ b/src/tools/clippy/clippy_lints/src/transmuting_null.rs @@ -31,7 +31,7 @@ const LINT_MSG: &str = "transmuting a known null pointer into a reference"; impl<'tcx> LateLintPass<'tcx> for TransmutingNull { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), cx.tcx.hir().span(expr.hir_id)) { return; } @@ -50,7 +50,7 @@ impl<'tcx> LateLintPass<'tcx> for TransmutingNull { let x = const_eval_context.expr(&args[0]); if let Some(Constant::RawPtr(0)) = x; then { - span_lint(cx, TRANSMUTING_NULL, expr.span, LINT_MSG) + span_lint(cx, TRANSMUTING_NULL, cx.tcx.hir().span(expr.hir_id), LINT_MSG) } } @@ -61,7 +61,7 @@ impl<'tcx> LateLintPass<'tcx> for TransmutingNull { if let ExprKind::Lit(ref lit) = inner_expr.kind; if let LitKind::Int(0, _) = lit.node; then { - span_lint(cx, TRANSMUTING_NULL, expr.span, LINT_MSG) + span_lint(cx, TRANSMUTING_NULL, cx.tcx.hir().span(expr.hir_id), LINT_MSG) } } @@ -73,7 +73,7 @@ impl<'tcx> LateLintPass<'tcx> for TransmutingNull { if match_qpath(path1, &paths::STD_PTR_NULL); if args1.is_empty(); then { - span_lint(cx, TRANSMUTING_NULL, expr.span, LINT_MSG) + span_lint(cx, TRANSMUTING_NULL, cx.tcx.hir().span(expr.hir_id), LINT_MSG) } } diff --git a/src/tools/clippy/clippy_lints/src/try_err.rs b/src/tools/clippy/clippy_lints/src/try_err.rs index 73e3a04aec987..91506ca11a193 100644 --- a/src/tools/clippy/clippy_lints/src/try_err.rs +++ b/src/tools/clippy/clippy_lints/src/try_err.rs @@ -59,7 +59,7 @@ impl<'tcx> LateLintPass<'tcx> for TryErr { // val, // }; if_chain! { - if !in_external_macro(cx.tcx.sess, expr.span); + if !in_external_macro(cx.tcx.sess, cx.tcx.hir().span(expr.hir_id)); if let ExprKind::Match(ref match_arg, _, MatchSource::TryDesugar) = expr.kind; if let ExprKind::Call(ref match_fun, ref try_args) = match_arg.kind; if let ExprKind::Path(ref match_fun_path) = match_fun.kind; @@ -92,14 +92,16 @@ impl<'tcx> LateLintPass<'tcx> for TryErr { }; let expr_err_ty = cx.typeck_results().expr_ty(err_arg); - let differing_contexts = differing_macro_contexts(expr.span, err_arg.span); - - let origin_snippet = if in_macro(expr.span) && in_macro(err_arg.span) && differing_contexts { - snippet(cx, err_arg.span.ctxt().outer_expn_data().call_site, "_") - } else if err_arg.span.from_expansion() && !in_macro(expr.span) { - snippet_with_macro_callsite(cx, err_arg.span, "_") + let expr_span = cx.tcx.hir().span(expr.hir_id); + let err_arg_span = cx.tcx.hir().span(err_arg.hir_id); + let differing_contexts = differing_macro_contexts(expr_span, err_arg_span); + + let origin_snippet = if in_macro(expr_span) && in_macro(err_arg_span) && differing_contexts { + snippet(cx, err_arg_span.ctxt().outer_expn_data().call_site, "_") + } else if err_arg_span.from_expansion() && !in_macro(expr_span) { + snippet_with_macro_callsite(cx, err_arg_span, "_") } else { - snippet(cx, err_arg.span, "_") + snippet(cx, err_arg_span, "_") }; let suggestion = if err_ty == expr_err_ty { format!("return {}{}{}", prefix, origin_snippet, suffix) @@ -110,7 +112,7 @@ impl<'tcx> LateLintPass<'tcx> for TryErr { span_lint_and_sugg( cx, TRY_ERR, - expr.span, + expr_span, "returning an `Err(_)` with the `?` operator", "try this", suggestion, diff --git a/src/tools/clippy/clippy_lints/src/types/mod.rs b/src/tools/clippy/clippy_lints/src/types/mod.rs index 0607b56dcdcfa..79354d3ffb6f6 100644 --- a/src/tools/clippy/clippy_lints/src/types/mod.rs +++ b/src/tools/clippy/clippy_lints/src/types/mod.rs @@ -430,7 +430,7 @@ impl<'tcx> LateLintPass<'tcx> for LetUnitValue { "this let-binding has unit value", |diag| { if let Some(expr) = &local.init { - let snip = snippet_with_macro_callsite(cx, expr.span, "()"); + let snip = snippet_with_macro_callsite(cx, cx.tcx.hir().span(expr.hir_id), "()"); diag.span_suggestion( stmt_span, "omit the `let` binding", @@ -496,8 +496,9 @@ declare_lint_pass!(UnitCmp => [UNIT_CMP]); impl<'tcx> LateLintPass<'tcx> for UnitCmp { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { - if expr.span.from_expansion() { - if let Some(callee) = expr.span.source_callee() { + let expr_span = cx.tcx.hir().span(expr.hir_id); + if expr_span.from_expansion() { + if let Some(callee) = expr_span.source_callee() { if let ExpnKind::Macro(MacroKind::Bang, symbol) = callee.kind { if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind { let op = cmp.node; @@ -510,7 +511,7 @@ impl<'tcx> LateLintPass<'tcx> for UnitCmp { span_lint( cx, UNIT_CMP, - expr.span, + expr_span, &format!( "`{}` of unit values detected. This will always {}", symbol.as_str(), @@ -533,7 +534,7 @@ impl<'tcx> LateLintPass<'tcx> for UnitCmp { span_lint( cx, UNIT_CMP, - expr.span, + expr_span, &format!( "{}-comparison of unit values detected. This will always be {}", op.as_str(), @@ -569,7 +570,7 @@ declare_lint_pass!(UnitArg => [UNIT_ARG]); impl<'tcx> LateLintPass<'tcx> for UnitArg { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if expr.span.from_expansion() { + if cx.tcx.hir().span(expr.hir_id).from_expansion() { return; } @@ -577,14 +578,14 @@ impl<'tcx> LateLintPass<'tcx> for UnitArg { // so check for that here // only the calls to `Try::from_error` is marked as desugared, // so we need to check both the current Expr and its parent. - if is_questionmark_desugar_marked_call(expr) { + if is_questionmark_desugar_marked_call(cx, expr) { return; } if_chain! { let map = &cx.tcx.hir(); let opt_parent_node = map.find(map.get_parent_node(expr.hir_id)); if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node; - if is_questionmark_desugar_marked_call(parent_expr); + if is_questionmark_desugar_marked_call(cx, parent_expr); then { return; } @@ -621,7 +622,7 @@ fn fmt_stmts_and_call( args_snippets: &[impl AsRef], non_empty_block_args_snippets: &[impl AsRef], ) -> String { - let call_expr_indent = indent_of(cx, call_expr.span).unwrap_or(0); + let call_expr_indent = indent_of(cx, cx.tcx.hir().span(call_expr.hir_id)).unwrap_or(0); let call_snippet_with_replacements = args_snippets .iter() .fold(call_snippet.to_owned(), |acc, arg| acc.replacen(arg.as_ref(), "()", 1)); @@ -660,10 +661,11 @@ fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Exp } else { ("a ", "") }; + let expr_span = cx.tcx.hir().span(expr.hir_id); span_lint_and_then( cx, UNIT_ARG, - expr.span, + expr_span, &format!("passing {}unit value{} to a function", singular, plural), |db| { let mut or = ""; @@ -675,7 +677,7 @@ fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Exp if block.expr.is_none(); if let Some(last_stmt) = block.stmts.iter().last(); if let StmtKind::Semi(last_expr) = last_stmt.kind; - if let Some(snip) = snippet_opt(cx, last_expr.span); + if let Some(snip) = snippet_opt(cx, cx.tcx.hir().span(last_expr.hir_id)); then { Some(( cx.tcx.hir().span(last_stmt.hir_id), @@ -700,15 +702,15 @@ fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Exp let arg_snippets: Vec = args_to_recover .iter() - .filter_map(|arg| snippet_opt(cx, arg.span)) + .filter_map(|arg| snippet_opt(cx, cx.tcx.hir().span(arg.hir_id))) .collect(); let arg_snippets_without_empty_blocks: Vec = args_to_recover .iter() .filter(|arg| !is_empty_block(arg)) - .filter_map(|arg| snippet_opt(cx, arg.span)) + .filter_map(|arg| snippet_opt(cx, cx.tcx.hir().span(arg.hir_id))) .collect(); - if let Some(call_snippet) = snippet_opt(cx, expr.span) { + if let Some(call_snippet) = snippet_opt(cx, cx.tcx.hir().span(expr.hir_id)) { let sugg = fmt_stmts_and_call( cx, expr, @@ -722,7 +724,7 @@ fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Exp &format!("use {}unit literal{} instead", singular, plural), args_to_recover .iter() - .map(|arg| (arg.span, "()".to_string())) + .map(|arg| (cx.tcx.hir().span(arg.hir_id), "()".to_string())) .collect::>(), applicability, ); @@ -731,7 +733,7 @@ fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Exp let empty_or_s = if plural { "s" } else { "" }; let it_or_them = if plural { "them" } else { "it" }; db.span_suggestion( - expr.span, + cx.tcx.hir().span(expr.hir_id), &format!( "{}move the expression{} in front of the call and replace {} with the unit literal `()`", or, empty_or_s, it_or_them @@ -759,10 +761,13 @@ fn is_empty_block(expr: &Expr<'_>) -> bool { ) } -fn is_questionmark_desugar_marked_call(expr: &Expr<'_>) -> bool { +fn is_questionmark_desugar_marked_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { use rustc_span::hygiene::DesugaringKind; if let ExprKind::Call(ref callee, _) = expr.kind { - callee.span.is_desugaring(DesugaringKind::QuestionMark) + cx.tcx + .hir() + .span(callee.hir_id) + .is_desugaring(DesugaringKind::QuestionMark) } else { false } @@ -1076,7 +1081,7 @@ impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons { if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind { if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) { - if !expr.span.from_expansion() { + if !cx.tcx.hir().span(expr.hir_id).from_expansion() { let msg = "this comparison involving the minimum or maximum element for this \ type contains a case that is always true or always false"; @@ -1086,14 +1091,14 @@ impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons { InequalityImpossible => format!( "the case where the two sides are not equal never occurs, consider using `{} == {}` \ instead", - snippet(cx, lhs.span, "lhs"), - snippet(cx, rhs.span, "rhs") + snippet(cx, cx.tcx.hir().span(lhs.hir_id), "lhs"), + snippet(cx, cx.tcx.hir().span(rhs.hir_id), "rhs") ), }; let help = format!( "because `{}` is the {} value for this type, {}", - snippet(cx, culprit.expr.span, "x"), + snippet(cx, cx.tcx.hir().span(culprit.expr.hir_id), "x"), match culprit.which { Minimum => "minimum", Maximum => "maximum", @@ -1101,7 +1106,14 @@ impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons { conclusion ); - span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help); + span_lint_and_help( + cx, + ABSURD_EXTREME_COMPARISONS, + cx.tcx.hir().span(expr.hir_id), + msg, + None, + &help, + ); } } } @@ -1232,7 +1244,7 @@ fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, alwa span, &format!( "because of the numeric bounds on `{}` prior to casting, this expression is always {}", - snippet(cx, cast_val.span, "the expression"), + snippet(cx, cx.tcx.hir().span(cast_val.hir_id), "the expression"), if always { "true" } else { "false" }, ), ); @@ -1310,8 +1322,9 @@ impl<'tcx> LateLintPass<'tcx> for InvalidUpcastComparisons { let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs); let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs); - upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false); - upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true); + let expr_span = cx.tcx.hir().span(expr.hir_id); + upcast_comparison_bounds_err(cx, expr_span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false); + upcast_comparison_bounds_err(cx, expr_span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true); } } } @@ -1632,29 +1645,30 @@ impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 't return; } + let e_span = self.cx.tcx.hir().span(e.hir_id); if match_path(ty_path, &paths::HASHMAP) { if method.ident.name == sym::new { self.suggestions - .insert(e.span, "HashMap::default()".to_string()); + .insert(e_span, "HashMap::default()".to_string()); } else if method.ident.name == sym!(with_capacity) { self.suggestions.insert( - e.span, + e_span, format!( "HashMap::with_capacity_and_hasher({}, Default::default())", - snippet(self.cx, args[0].span, "capacity"), + snippet(self.cx, self.cx.tcx.hir().span(args[0].hir_id), "capacity"), ), ); } } else if match_path(ty_path, &paths::HASHSET) { if method.ident.name == sym::new { self.suggestions - .insert(e.span, "HashSet::default()".to_string()); + .insert(e_span, "HashSet::default()".to_string()); } else if method.ident.name == sym!(with_capacity) { self.suggestions.insert( - e.span, + e_span, format!( "HashSet::with_capacity_and_hasher({}, Default::default())", - snippet(self.cx, args[0].span, "capacity"), + snippet(self.cx, self.cx.tcx.hir().span(args[0].hir_id), "capacity"), ), ); } diff --git a/src/tools/clippy/clippy_lints/src/undropped_manually_drops.rs b/src/tools/clippy/clippy_lints/src/undropped_manually_drops.rs index 5443f1601fcbb..41901d8fcce94 100644 --- a/src/tools/clippy/clippy_lints/src/undropped_manually_drops.rs +++ b/src/tools/clippy/clippy_lints/src/undropped_manually_drops.rs @@ -39,7 +39,7 @@ impl LateLintPass<'tcx> for UndroppedManuallyDrops { span_lint_and_help( cx, UNDROPPED_MANUALLY_DROPS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "the inner value of this ManuallyDrop will not be dropped", None, "to drop a `ManuallyDrop`, use std::mem::ManuallyDrop::drop", diff --git a/src/tools/clippy/clippy_lints/src/unnamed_address.rs b/src/tools/clippy/clippy_lints/src/unnamed_address.rs index 9582c162e77b2..a6246426bd799 100644 --- a/src/tools/clippy/clippy_lints/src/unnamed_address.rs +++ b/src/tools/clippy/clippy_lints/src/unnamed_address.rs @@ -83,7 +83,7 @@ impl LateLintPass<'_> for UnnamedAddress { span_lint_and_help( cx, VTABLE_ADDRESS_COMPARISONS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "comparing trait object pointers compares a non-unique vtable address", None, "consider extracting and comparing data pointers only", @@ -104,7 +104,7 @@ impl LateLintPass<'_> for UnnamedAddress { span_lint_and_help( cx, VTABLE_ADDRESS_COMPARISONS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "comparing trait object pointers compares a non-unique vtable address", None, "consider extracting and comparing data pointers only", @@ -122,7 +122,7 @@ impl LateLintPass<'_> for UnnamedAddress { span_lint( cx, FN_ADDRESS_COMPARISONS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "comparing with a non-unique address of a function item", ); } diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_sort_by.rs b/src/tools/clippy/clippy_lints/src/unnecessary_sort_by.rs index 00a707107bce9..11d5acfc881f7 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_sort_by.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_sort_by.rs @@ -235,7 +235,7 @@ impl LateLintPass<'_> for UnnecessarySortBy { Some(LintTrigger::SortByKey(trigger)) => utils::span_lint_and_sugg( cx, UNNECESSARY_SORT_BY, - expr.span, + cx.tcx.hir().span(expr.hir_id), "use Vec::sort_by_key here instead", "try", format!( @@ -258,7 +258,7 @@ impl LateLintPass<'_> for UnnecessarySortBy { Some(LintTrigger::Sort(trigger)) => utils::span_lint_and_sugg( cx, UNNECESSARY_SORT_BY, - expr.span, + cx.tcx.hir().span(expr.hir_id), "use Vec::sort here instead", "try", format!( diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs index 82efb0bf0125f..170726ad15354 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs @@ -100,7 +100,7 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryWraps { let mut suggs = Vec::new(); let can_sugg = find_all_ret_expressions(cx, &body.value, |ret_expr| { if_chain! { - if !in_macro(ret_expr.span); + if !in_macro(cx.tcx.hir().span(ret_expr.hir_id)); // Check if a function call. if let ExprKind::Call(ref func, ref args) = ret_expr.kind; // Get the Path of the function call. @@ -113,11 +113,11 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryWraps { then { suggs.push( ( - ret_expr.span, + cx.tcx.hir().span(ret_expr.hir_id), if inner_type.is_unit() { "".to_string() } else { - snippet(cx, args[0].span.source_callsite(), "..").to_string() + snippet(cx, cx.tcx.hir().span(args[0].hir_id).source_callsite(), "..").to_string() } ) ); diff --git a/src/tools/clippy/clippy_lints/src/unused_io_amount.rs b/src/tools/clippy/clippy_lints/src/unused_io_amount.rs index 43166d26787a7..661d36e40f3af 100644 --- a/src/tools/clippy/clippy_lints/src/unused_io_amount.rs +++ b/src/tools/clippy/clippy_lints/src/unused_io_amount.rs @@ -70,22 +70,23 @@ fn check_method_call(cx: &LateContext<'_>, call: &hir::Expr<'_>, expr: &hir::Exp let symbol = &*path.ident.as_str(); let read_trait = match_trait_method(cx, call, &paths::IO_READ); let write_trait = match_trait_method(cx, call, &paths::IO_WRITE); + let expr_span = cx.tcx.hir().span(expr.hir_id); match (read_trait, write_trait, symbol) { (true, _, "read") => span_lint( cx, UNUSED_IO_AMOUNT, - expr.span, + expr_span, "read amount is not handled. Use `Read::read_exact` instead", ), - (true, _, "read_vectored") => span_lint(cx, UNUSED_IO_AMOUNT, expr.span, "read amount is not handled"), + (true, _, "read_vectored") => span_lint(cx, UNUSED_IO_AMOUNT, expr_span, "read amount is not handled"), (_, true, "write") => span_lint( cx, UNUSED_IO_AMOUNT, - expr.span, + expr_span, "written amount is not handled. Use `Write::write_all` instead", ), - (_, true, "write_vectored") => span_lint(cx, UNUSED_IO_AMOUNT, expr.span, "written amount is not handled"), + (_, true, "write_vectored") => span_lint(cx, UNUSED_IO_AMOUNT, expr_span, "written amount is not handled"), _ => (), } } diff --git a/src/tools/clippy/clippy_lints/src/unwrap.rs b/src/tools/clippy/clippy_lints/src/unwrap.rs index 988148aec0bef..ef37987d93a5a 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap.rs @@ -153,7 +153,7 @@ impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> { fn visit_expr(&mut self, expr: &'tcx Expr<'_>) { // Shouldn't lint when `expr` is in macro. - if in_external_macro(self.cx.tcx.sess, expr.span) { + if in_external_macro(self.cx.tcx.sess, self.cx.tcx.hir().span(expr.hir_id)) { return; } if let ExprKind::If(cond, then, els) = &expr.kind { @@ -172,27 +172,27 @@ impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> { if let Some(unwrappable) = self.unwrappables.iter() .find(|u| u.ident.res == path.res); // Span contexts should not differ with the conditional branch - if !differing_macro_contexts(unwrappable.branch.span, expr.span); - if !differing_macro_contexts(unwrappable.branch.span, unwrappable.check.span); + if !differing_macro_contexts(self.cx.tcx.hir().span(unwrappable.branch.hir_id), self.cx.tcx.hir().span(expr.hir_id)); + if !differing_macro_contexts(self.cx.tcx.hir().span(unwrappable.branch.hir_id), self.cx.tcx.hir().span(unwrappable.check.hir_id)); then { if call_to_unwrap == unwrappable.safe_to_unwrap { span_lint_and_then( self.cx, UNNECESSARY_UNWRAP, - expr.span, + self.cx.tcx.hir().span(expr.hir_id), &format!("you checked before that `{}()` cannot fail, \ instead of checking and unwrapping, it's better to use `if let` or `match`", method_name.ident.name), - |diag| { diag.span_label(unwrappable.check.span, "the check is happening here"); }, + |diag| { diag.span_label(self.cx.tcx.hir().span(unwrappable.check.hir_id), "the check is happening here"); }, ); } else { span_lint_and_then( self.cx, PANICKING_UNWRAP, - expr.span, + self.cx.tcx.hir().span(expr.hir_id), &format!("this call to `{}()` will always panic", method_name.ident.name), - |diag| { diag.span_label(unwrappable.check.span, "because of this check"); }, + |diag| { diag.span_label(self.cx.tcx.hir().span(unwrappable.check.hir_id), "because of this check"); }, ); } } diff --git a/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs b/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs index 3c15b52500d2f..5607fa962bcb5 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs @@ -80,22 +80,22 @@ impl<'a, 'tcx> Visitor<'tcx> for FindExpectUnwrap<'a, 'tcx> { fn visit_expr(&mut self, expr: &'tcx Expr<'_>) { // check for `expect` - if let Some(arglists) = method_chain_args(expr, &["expect"]) { + if let Some(arglists) = method_chain_args(self.lcx, expr, &["expect"]) { let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs(); if is_type_diagnostic_item(self.lcx, reciever_ty, sym::option_type) || is_type_diagnostic_item(self.lcx, reciever_ty, sym::result_type) { - self.result.push(expr.span); + self.result.push(self.lcx.tcx.hir().span(expr.hir_id)); } } // check for `unwrap` - if let Some(arglists) = method_chain_args(expr, &["unwrap"]) { + if let Some(arglists) = method_chain_args(self.lcx, expr, &["unwrap"]) { let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs(); if is_type_diagnostic_item(self.lcx, reciever_ty, sym::option_type) || is_type_diagnostic_item(self.lcx, reciever_ty, sym::result_type) { - self.result.push(expr.span); + self.result.push(self.lcx.tcx.hir().span(expr.hir_id)); } } diff --git a/src/tools/clippy/clippy_lints/src/useless_conversion.rs b/src/tools/clippy/clippy_lints/src/useless_conversion.rs index c533485398605..9fb06605f3e26 100644 --- a/src/tools/clippy/clippy_lints/src/useless_conversion.rs +++ b/src/tools/clippy/clippy_lints/src/useless_conversion.rs @@ -44,7 +44,7 @@ impl_lint_pass!(UselessConversion => [USELESS_CONVERSION]); #[allow(clippy::too_many_lines)] impl<'tcx> LateLintPass<'tcx> for UselessConversion { fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { - if e.span.from_expansion() { + if cx.tcx.hir().span(e.hir_id).from_expansion() { return; } @@ -68,11 +68,11 @@ impl<'tcx> LateLintPass<'tcx> for UselessConversion { let a = cx.typeck_results().expr_ty(e); let b = cx.typeck_results().expr_ty(&args[0]); if TyS::same_type(a, b) { - let sugg = snippet_with_macro_callsite(cx, args[0].span, "").to_string(); + let sugg = snippet_with_macro_callsite(cx, cx.tcx.hir().span(args[0].hir_id), "").to_string(); span_lint_and_sugg( cx, USELESS_CONVERSION, - e.span, + cx.tcx.hir().span(e.hir_id), &format!("useless conversion to the same type: `{}`", b), "consider removing `.into()`", sugg, @@ -91,11 +91,11 @@ impl<'tcx> LateLintPass<'tcx> for UselessConversion { let a = cx.typeck_results().expr_ty(e); let b = cx.typeck_results().expr_ty(&args[0]); if TyS::same_type(a, b) { - let sugg = snippet(cx, args[0].span, "").into_owned(); + let sugg = snippet(cx, cx.tcx.hir().span(args[0].hir_id), "").into_owned(); span_lint_and_sugg( cx, USELESS_CONVERSION, - e.span, + cx.tcx.hir().span(e.hir_id), &format!("useless conversion to the same type: `{}`", b), "consider removing `.into_iter()`", sugg, @@ -116,7 +116,7 @@ impl<'tcx> LateLintPass<'tcx> for UselessConversion { span_lint_and_help( cx, USELESS_CONVERSION, - e.span, + cx.tcx.hir().span(e.hir_id), &format!("useless conversion to the same type: `{}`", b), None, "consider removing `.try_into()`", @@ -143,11 +143,11 @@ impl<'tcx> LateLintPass<'tcx> for UselessConversion { if TyS::same_type(a_type, b); then { - let hint = format!("consider removing `{}()`", snippet(cx, path.span, "TryFrom::try_from")); + let hint = format!("consider removing `{}()`", snippet(cx, cx.tcx.hir().span(path.hir_id), "TryFrom::try_from")); span_lint_and_help( cx, USELESS_CONVERSION, - e.span, + cx.tcx.hir().span(e.hir_id), &format!("useless conversion to the same type: `{}`", b), None, &hint, @@ -162,11 +162,11 @@ impl<'tcx> LateLintPass<'tcx> for UselessConversion { then { let sugg = Sugg::hir_with_macro_callsite(cx, &args[0], "").maybe_par(); let sugg_msg = - format!("consider removing `{}()`", snippet(cx, path.span, "From::from")); + format!("consider removing `{}()`", snippet(cx, cx.tcx.hir().span(path.hir_id), "From::from")); span_lint_and_sugg( cx, USELESS_CONVERSION, - e.span, + cx.tcx.hir().span(e.hir_id), &format!("useless conversion to the same type: `{}`", b), &sugg_msg, sugg.to_string(), diff --git a/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs b/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs index 38b87db135358..509769eef3d8e 100644 --- a/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs +++ b/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs @@ -516,7 +516,7 @@ impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass { return; } - let (method_names, arg_lists, spans) = method_calls(expr, 2); + let (method_names, arg_lists, spans) = method_calls(cx, expr, 2); let method_names: Vec = method_names.iter().map(|s| s.as_str()).collect(); let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect(); if_chain! { @@ -530,7 +530,7 @@ impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass { span_lint_and_sugg( cx, OUTER_EXPN_EXPN_DATA, - spans[1].with_hi(expr.span.hi()), + spans[1].with_hi(cx.tcx.hir().span(expr.hir_id).hi()), "usage of `outer_expn().expn_data()`", "try", "outer_expn_data()".to_string(), @@ -586,19 +586,19 @@ impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls { suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args)); }, "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => { - let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#); + let help_snippet = snippet(cx, cx.tcx.hir().span(span_call_args[2].hir_id), r#""...""#); suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true); }, "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => { - let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#); + let note_snippet = snippet(cx, cx.tcx.hir().span(span_call_args[2].hir_id), r#""...""#); suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true); }, "help" => { - let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#); + let help_snippet = snippet(cx, cx.tcx.hir().span(span_call_args[1].hir_id), r#""...""#); suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false); } "note" => { - let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#); + let note_snippet = snippet(cx, cx.tcx.hir().span(span_call_args[1].hir_id), r#""...""#); suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false); } _ => (), @@ -615,11 +615,14 @@ struct AndThenSnippets<'a> { msg: Cow<'a, str>, } -fn get_and_then_snippets<'a, 'hir>(cx: &LateContext<'_>, and_then_snippets: &'hir [Expr<'hir>]) -> AndThenSnippets<'a> { - let cx_snippet = snippet(cx, and_then_snippets[0].span, "cx"); - let lint_snippet = snippet(cx, and_then_snippets[1].span, ".."); - let span_snippet = snippet(cx, and_then_snippets[2].span, "span"); - let msg_snippet = snippet(cx, and_then_snippets[3].span, r#""...""#); +fn get_and_then_snippets<'a, 'hir>( + cx: &LateContext<'_>, + and_then_snippets: &'hir [Expr<'hir>], +) -> AndThenSnippets<'a> { + let cx_snippet = snippet(cx, cx.tcx.hir().span(and_then_snippets[0].hir_id), "cx"); + let lint_snippet = snippet(cx, cx.tcx.hir().span(and_then_snippets[1].hir_id), ".."); + let span_snippet = snippet(cx, cx.tcx.hir().span(and_then_snippets[2].hir_id), "span"); + let msg_snippet = snippet(cx, cx.tcx.hir().span(and_then_snippets[3].hir_id), r#""...""#); AndThenSnippets { cx: cx_snippet, @@ -639,9 +642,9 @@ fn span_suggestion_snippets<'a, 'hir>( cx: &LateContext<'_>, span_call_args: &'hir [Expr<'hir>], ) -> SpanSuggestionSnippets<'a> { - let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#); - let sugg_snippet = snippet(cx, span_call_args[3].span, ".."); - let applicability_snippet = snippet(cx, span_call_args[4].span, "Applicability::MachineApplicable"); + let help_snippet = snippet(cx, cx.tcx.hir().span(span_call_args[2].hir_id), r#""...""#); + let sugg_snippet = snippet(cx, cx.tcx.hir().span(span_call_args[3].hir_id), ".."); + let applicability_snippet = snippet(cx, cx.tcx.hir().span(span_call_args[4].hir_id), "Applicability::MachineApplicable"); SpanSuggestionSnippets { help: help_snippet, @@ -659,7 +662,7 @@ fn suggest_suggestion( span_lint_and_sugg( cx, COLLAPSIBLE_SPAN_LINT_CALLS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "this call is collapsible", "collapse into", format!( @@ -692,7 +695,7 @@ fn suggest_help( span_lint_and_sugg( cx, COLLAPSIBLE_SPAN_LINT_CALLS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "this call is collapsible", "collapse into", format!( @@ -724,7 +727,7 @@ fn suggest_note( span_lint_and_sugg( cx, COLLAPSIBLE_SPAN_LINT_CALLS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "this call is collspible", "collapse into", format!( @@ -761,13 +764,13 @@ impl<'tcx> LateLintPass<'tcx> for MatchTypeOnDiagItem { let diag_items = cx.tcx.diagnostic_items(ty_did.krate); if let Some(item_name) = diag_items.iter().find_map(|(k, v)| if *v == ty_did { Some(k) } else { None }); then { - let cx_snippet = snippet(cx, context.span, "_"); - let ty_snippet = snippet(cx, ty.span, "_"); + let cx_snippet = snippet(cx, cx.tcx.hir().span(context.hir_id), "_"); + let ty_snippet = snippet(cx, cx.tcx.hir().span(ty.hir_id), "_"); span_lint_and_sugg( cx, MATCH_TYPE_ON_DIAGNOSTIC_ITEM, - expr.span, + cx.tcx.hir().span(expr.hir_id), "usage of `utils::match_type()` on a type diagnostic item", "try", format!("utils::is_type_diagnostic_item({}, {}, sym::{})", cx_snippet, ty_snippet, item_name), diff --git a/src/tools/clippy/clippy_lints/src/vec.rs b/src/tools/clippy/clippy_lints/src/vec.rs index c5a930e4c6e0b..df8dbc28ec335 100644 --- a/src/tools/clippy/clippy_lints/src/vec.rs +++ b/src/tools/clippy/clippy_lints/src/vec.rs @@ -49,7 +49,7 @@ impl<'tcx> LateLintPass<'tcx> for UselessVec { if let ExprKind::AddrOf(BorrowKind::Ref, _, ref addressee) = expr.kind; if let Some(vec_args) = higher::vec_macro(cx, addressee); then { - self.check_vec_macro(cx, &vec_args, expr.span); + self.check_vec_macro(cx, &vec_args, cx.tcx.hir().span(expr.hir_id)); } } @@ -60,7 +60,7 @@ impl<'tcx> LateLintPass<'tcx> for UselessVec { if is_copy(cx, vec_type(cx.typeck_results().expr_ty_adjusted(arg))); then { // report the error around the `vec!` not inside `:` - let span = arg.span + let span = cx.tcx.hir().span(arg.hir_id) .ctxt() .outer_expn_data() .call_site @@ -86,8 +86,8 @@ impl UselessVec { format!( "&[{}; {}]", - snippet_with_applicability(cx, elem.span, "elem", &mut applicability), - snippet_with_applicability(cx, len.span, "len", &mut applicability) + snippet_with_applicability(cx, cx.tcx.hir().span(elem.hir_id), "elem", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(len.hir_id), "len", &mut applicability) ) } else { return; @@ -99,7 +99,7 @@ impl UselessVec { if args.len() as u64 * size_of(cx, last) > self.too_large_for_stack { return; } - let span = args[0].span.to(last.span); + let span = cx.tcx.hir().span(args[0].hir_id).to(cx.tcx.hir().span(last.hir_id)); format!("&[{}]", snippet_with_applicability(cx, span, "..", &mut applicability)) } else { diff --git a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs index 8040faab01fcf..a8cee16f48a98 100644 --- a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs +++ b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs @@ -111,17 +111,19 @@ impl LateLintPass<'_> for VecInitThenPush { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if self.searcher.is_none() { if_chain! { - if !in_external_macro(cx.sess(), expr.span); + let expr_span = cx.tcx.hir().span(expr.hir_id); + if !in_external_macro(cx.sess(), expr_span); if let ExprKind::Assign(left, right, _) = expr.kind; if let Some(id) = path_to_local(left); if let Some(init_kind) = get_vec_init_kind(cx, right); then { + let left_span = cx.tcx.hir().span(left.hir_id); self.searcher = Some(VecPushSearcher { local_id: id, init: init_kind, lhs_is_local: false, - lhs_span: left.span, - err_span: expr.span, + lhs_span: left_span, + err_span: expr_span, found: 0, }); } diff --git a/src/tools/clippy/clippy_lints/src/vec_resize_to_zero.rs b/src/tools/clippy/clippy_lints/src/vec_resize_to_zero.rs index d2494b321efcd..4439a14671136 100644 --- a/src/tools/clippy/clippy_lints/src/vec_resize_to_zero.rs +++ b/src/tools/clippy/clippy_lints/src/vec_resize_to_zero.rs @@ -37,11 +37,12 @@ impl<'tcx> LateLintPass<'tcx> for VecResizeToZero { if let ExprKind::Lit(Spanned { node: LitKind::Int(0, _), .. }) = args[1].kind; if let ExprKind::Lit(Spanned { node: LitKind::Int(..), .. }) = args[2].kind; then { - let method_call_span = expr.span.with_lo(path_segment.ident.span.lo()); + let expr_span = cx.tcx.hir().span(expr.hir_id); + let method_call_span = expr_span.with_lo(path_segment.ident.span.lo()); span_lint_and_then( cx, VEC_RESIZE_TO_ZERO, - expr.span, + expr_span, "emptying a vector with `resize`", |db| { db.help("the arguments may be inverted..."); diff --git a/src/tools/clippy/clippy_lints/src/verbose_file_reads.rs b/src/tools/clippy/clippy_lints/src/verbose_file_reads.rs index 32574d9d6c9a8..08791fe0d433d 100644 --- a/src/tools/clippy/clippy_lints/src/verbose_file_reads.rs +++ b/src/tools/clippy/clippy_lints/src/verbose_file_reads.rs @@ -39,7 +39,7 @@ impl<'tcx> LateLintPass<'tcx> for VerboseFileReads { span_lint_and_help( cx, VERBOSE_FILE_READS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "use of `File::read_to_end`", None, "consider using `fs::read` instead", @@ -48,7 +48,7 @@ impl<'tcx> LateLintPass<'tcx> for VerboseFileReads { span_lint_and_help( cx, VERBOSE_FILE_READS, - expr.span, + cx.tcx.hir().span(expr.hir_id), "use of `File::read_to_string`", None, "consider using `fs::read_to_string` instead", diff --git a/src/tools/clippy/clippy_lints/src/zero_div_zero.rs b/src/tools/clippy/clippy_lints/src/zero_div_zero.rs index 11d96e15ff151..b866c5cdb89f5 100644 --- a/src/tools/clippy/clippy_lints/src/zero_div_zero.rs +++ b/src/tools/clippy/clippy_lints/src/zero_div_zero.rs @@ -51,7 +51,7 @@ impl<'tcx> LateLintPass<'tcx> for ZeroDiv { span_lint_and_help( cx, ZERO_DIVIDED_BY_ZERO, - expr.span, + cx.tcx.hir().span(expr.hir_id), "constant division of `0.0` with `0.0` will always result in NaN", None, &format!( diff --git a/src/tools/clippy/clippy_utils/src/consts.rs b/src/tools/clippy/clippy_utils/src/consts.rs index 802c01055a68c..42eb90594759a 100644 --- a/src/tools/clippy/clippy_utils/src/consts.rs +++ b/src/tools/clippy/clippy_utils/src/consts.rs @@ -237,7 +237,7 @@ impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> { ExprKind::Repeat(ref value, _) => { let n = match self.typeck_results.expr_ty(e).kind() { ty::Array(_, n) => n.try_eval_usize(self.lcx.tcx, self.lcx.param_env)?, - _ => span_bug!(e.span, "typeck error"), + _ => span_bug!(self.lcx.tcx.hir().span(e.hir_id), "typeck error"), }; self.expr(value).map(|v| Constant::Repeat(Box::new(v), n)) }, diff --git a/src/tools/clippy/clippy_utils/src/higher.rs b/src/tools/clippy/clippy_utils/src/higher.rs index 3a8afbf6284fa..ea7276b35c47d 100644 --- a/src/tools/clippy/clippy_utils/src/higher.rs +++ b/src/tools/clippy/clippy_utils/src/higher.rs @@ -185,7 +185,7 @@ pub fn vec_macro<'e>(cx: &LateContext<'_>, expr: &'e hir::Expr<'_>) -> Option { #[allow(clippy::similar_names)] fn eq_expr(&mut self, left: &Expr<'_>, right: &Expr<'_>) -> bool { - if !self.inner.allow_side_effects && differing_macro_contexts(left.span, right.span) { + if !self.inner.allow_side_effects + && differing_macro_contexts( + self.inner.cx.tcx.hir().span(left.hir_id), + self.inner.cx.tcx.hir().span(right.hir_id), + ) + { return false; } diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index 10412573d8599..bf11b6e38314a 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -549,6 +549,7 @@ pub fn can_partially_move_ty(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { /// Returns the method names and argument list of nested method call expressions that make up /// `expr`. method/span lists are sorted with the most recent call first. pub fn method_calls<'tcx>( + cx: &LateContext<'_>, expr: &'tcx Expr<'tcx>, max_depth: usize, ) -> (Vec, Vec<&'tcx [Expr<'tcx>]>, Vec) { @@ -559,7 +560,7 @@ pub fn method_calls<'tcx>( let mut current = expr; for _ in 0..max_depth { if let ExprKind::MethodCall(path, span, args, _) = ¤t.kind { - if args.iter().any(|e| e.span.from_expansion()) { + if args.iter().any(|e| cx.tcx.hir().span(e.hir_id).from_expansion()) { break; } method_names.push(path.ident.name); @@ -580,14 +581,18 @@ pub fn method_calls<'tcx>( /// `method_chain_args(expr, &["bar", "baz"])` will return a `Vec` /// containing the `Expr`s for /// `.bar()` and `.baz()` -pub fn method_chain_args<'a>(expr: &'a Expr<'_>, methods: &[&str]) -> Option]>> { +pub fn method_chain_args<'a>( + cx: &LateContext<'_>, + expr: &'a Expr<'_>, + methods: &[&str], +) -> Option]>> { let mut current = expr; let mut matched = Vec::with_capacity(methods.len()); for method_name in methods.iter().rev() { // method chains are stored last -> first if let ExprKind::MethodCall(ref path, _, ref args, _) = current.kind { if path.ident.name.as_str() == *method_name { - if args.iter().any(|e| e.span.from_expansion()) { + if args.iter().any(|e| cx.tcx.hir().span(e.hir_id).from_expansion()) { return None; } matched.push(&**args); // build up `matched` backwards @@ -696,17 +701,19 @@ pub fn contains_return(expr: &hir::Expr<'_>) -> bool { visitor.found } -struct FindMacroCalls<'a, 'b> { +struct FindMacroCalls<'tcx, 'a, 'b> { + tcx: TyCtxt<'tcx>, names: &'a [&'b str], result: Vec, } -impl<'a, 'b, 'tcx> Visitor<'tcx> for FindMacroCalls<'a, 'b> { - type Map = Map<'tcx>; +impl<'a, 'b, 'tcx, 'hir> Visitor<'hir> for FindMacroCalls<'tcx, 'a, 'b> { + type Map = Map<'hir>; - fn visit_expr(&mut self, expr: &'tcx Expr<'_>) { - if self.names.iter().any(|fun| is_expn_of(expr.span, fun).is_some()) { - self.result.push(expr.span); + fn visit_expr(&mut self, expr: &'hir Expr<'_>) { + let expr_span = self.tcx.hir().span(expr.hir_id); + if self.names.iter().any(|fun| is_expn_of(expr_span, fun).is_some()) { + self.result.push(expr_span); } // and check sub-expressions intravisit::walk_expr(self, expr); @@ -718,8 +725,9 @@ impl<'a, 'b, 'tcx> Visitor<'tcx> for FindMacroCalls<'a, 'b> { } /// Finds calls of the specified macros in a function body. -pub fn find_macro_calls(names: &[&str], body: &Body<'_>) -> Vec { +pub fn find_macro_calls(tcx: TyCtxt<'_>, names: &[&str], body: &Body<'_>) -> Vec { let mut fmc = FindMacroCalls { + tcx, names, result: Vec::new(), }; @@ -946,17 +954,18 @@ fn line_span(cx: &T, span: Span) -> Span { /// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`. /// Also takes an `Option` which can be put inside the braces. -pub fn expr_block<'a, T: LintContext>( - cx: &T, +pub fn expr_block<'a>( + cx: &LateContext<'_>, expr: &Expr<'_>, option: Option, default: &'a str, indent_relative_to: Option, ) -> Cow<'a, str> { - let code = snippet_block(cx, expr.span, default, indent_relative_to); + let expr_span = cx.tcx.hir().span(expr.hir_id); + let code = snippet_block(cx, expr_span, default, indent_relative_to); let string = option.unwrap_or_default(); - if expr.span.from_expansion() { - Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default))) + if expr_span.from_expansion() { + Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr_span, default))) } else if let ExprKind::Block(_, _) = expr.kind { Cow::Owned(format!("{}{}", code, string)) } else if string.is_empty() { diff --git a/src/tools/clippy/clippy_utils/src/ptr.rs b/src/tools/clippy/clippy_utils/src/ptr.rs index df6143edbcaf0..7908609640646 100644 --- a/src/tools/clippy/clippy_utils/src/ptr.rs +++ b/src/tools/clippy/clippy_utils/src/ptr.rs @@ -63,7 +63,7 @@ impl<'a, 'tcx> Visitor<'tcx> for PtrCloneVisitor<'a, 'tcx> { for &(fn_name, suffix) in self.replace { if seg.ident.name.as_str() == fn_name { self.spans - .push((expr.span, snippet(self.cx, args[0].span, "_") + suffix)); + .push((self.cx.tcx.hir().span(expr.hir_id), snippet(self.cx, self.cx.tcx.hir().span(args[0].hir_id), "_") + suffix)); return; } } diff --git a/src/tools/clippy/clippy_utils/src/sugg.rs b/src/tools/clippy/clippy_utils/src/sugg.rs index d4f6f4281d368..cc6d97453ca2e 100644 --- a/src/tools/clippy/clippy_utils/src/sugg.rs +++ b/src/tools/clippy/clippy_utils/src/sugg.rs @@ -46,7 +46,7 @@ impl Display for Sugg<'_> { impl<'a> Sugg<'a> { /// Prepare a suggestion from an expression. pub fn hir_opt(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option { - snippet_opt(cx, expr.span).map(|snippet| { + snippet_opt(cx, cx.tcx.hir().span(expr.hir_id)).map(|snippet| { let snippet = Cow::Owned(snippet); Self::hir_from_snippet(expr, snippet) }) @@ -71,7 +71,7 @@ impl<'a> Sugg<'a> { default: &'a str, applicability: &mut Applicability, ) -> Self { - if *applicability != Applicability::Unspecified && expr.span.from_expansion() { + if *applicability != Applicability::Unspecified && cx.tcx.hir().span(expr.hir_id).from_expansion() { *applicability = Applicability::MaybeIncorrect; } Self::hir_opt(cx, expr).unwrap_or_else(|| { @@ -84,7 +84,7 @@ impl<'a> Sugg<'a> { /// Same as `hir`, but will use the pre expansion span if the `expr` was in a macro. pub fn hir_with_macro_callsite(cx: &LateContext<'_>, expr: &hir::Expr<'_>, default: &'a str) -> Self { - let snippet = snippet_with_macro_callsite(cx, expr.span, default); + let snippet = snippet_with_macro_callsite(cx, cx.tcx.hir().span(expr.hir_id), default); Self::hir_from_snippet(expr, snippet) } diff --git a/src/tools/clippy/clippy_utils/src/usage.rs b/src/tools/clippy/clippy_utils/src/usage.rs index d577827dcf3cc..3721c07e65fa0 100644 --- a/src/tools/clippy/clippy_utils/src/usage.rs +++ b/src/tools/clippy/clippy_utils/src/usage.rs @@ -8,7 +8,7 @@ use rustc_hir::{Expr, ExprKind, HirId, Path}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; use rustc_middle::hir::map::Map; -use rustc_middle::ty; +use rustc_middle::ty::{self, TyCtxt}; use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; /// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined. @@ -150,19 +150,21 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for BindingUsageFinder<'a, 'tcx> { } } -struct ReturnBreakContinueMacroVisitor { +struct ReturnBreakContinueMacroVisitor<'tcx> { + tcx: TyCtxt<'tcx>, seen_return_break_continue: bool, } -impl ReturnBreakContinueMacroVisitor { - fn new() -> ReturnBreakContinueMacroVisitor { +impl<'tcx> ReturnBreakContinueMacroVisitor<'tcx> { + fn new(tcx: TyCtxt<'tcx>) -> ReturnBreakContinueMacroVisitor<'tcx> { ReturnBreakContinueMacroVisitor { + tcx, seen_return_break_continue: false, } } } -impl<'tcx> Visitor<'tcx> for ReturnBreakContinueMacroVisitor { +impl<'tcx> Visitor<'tcx> for ReturnBreakContinueMacroVisitor<'_> { type Map = Map<'tcx>; fn nested_visit_map(&mut self) -> NestedVisitorMap { NestedVisitorMap::None @@ -181,7 +183,7 @@ impl<'tcx> Visitor<'tcx> for ReturnBreakContinueMacroVisitor { // desugaring, as this will detect a break if there's a while loop // or a for loop inside the expression. _ => { - if utils::in_macro(ex.span) { + if utils::in_macro(self.tcx.hir().span(ex.hir_id)) { self.seen_return_break_continue = true; } else { rustc_hir::intravisit::walk_expr(self, ex); @@ -191,8 +193,8 @@ impl<'tcx> Visitor<'tcx> for ReturnBreakContinueMacroVisitor { } } -pub fn contains_return_break_continue_macro(expression: &Expr<'_>) -> bool { - let mut recursive_visitor = ReturnBreakContinueMacroVisitor::new(); +pub fn contains_return_break_continue_macro(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool { + let mut recursive_visitor = ReturnBreakContinueMacroVisitor::new(cx.tcx); recursive_visitor.visit_expr(expression); recursive_visitor.seen_return_break_continue } From f0656568b8c13c155401423da6bc21dd0d496341 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 9 May 2020 12:23:57 +0200 Subject: [PATCH 40/41] Fix fulldeps tests. --- src/test/ui-fulldeps/auxiliary/lint-group-plugin-test.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/test/ui-fulldeps/auxiliary/lint-group-plugin-test.rs b/src/test/ui-fulldeps/auxiliary/lint-group-plugin-test.rs index 02216b33dc3ad..907f75140b524 100644 --- a/src/test/ui-fulldeps/auxiliary/lint-group-plugin-test.rs +++ b/src/test/ui-fulldeps/auxiliary/lint-group-plugin-test.rs @@ -12,7 +12,7 @@ extern crate rustc_lint; extern crate rustc_session; use rustc_driver::plugin::Registry; -use rustc_lint::{LateContext, LateLintPass, LintArray, LintContext, LintId, LintPass}; +use rustc_lint::{LateContext, LateLintPass, LintContext, LintId}; declare_lint!(TEST_LINT, Warn, "Warn about items named 'lintme'"); @@ -22,12 +22,13 @@ declare_lint_pass!(Pass => [TEST_LINT, PLEASE_LINT]); impl<'tcx> LateLintPass<'tcx> for Pass { fn check_item(&mut self, cx: &LateContext, it: &rustc_hir::Item) { + let it_span = cx.tcx.hir().span_with_body(it.hir_id()); match &*it.ident.as_str() { "lintme" => cx.lint(TEST_LINT, |lint| { - lint.build("item is named 'lintme'").set_span(it.span).emit() + lint.build("item is named 'lintme'").set_span(it_span).emit() }), "pleaselintme" => cx.lint(PLEASE_LINT, |lint| { - lint.build("item is named 'pleaselintme'").set_span(it.span).emit() + lint.build("item is named 'pleaselintme'").set_span(it_span).emit() }), _ => {} } From bb40d089953ffca7641b737f3c7ecf9a39b70625 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 13 Mar 2021 22:34:48 +0100 Subject: [PATCH 41/41] Fix suggestions. --- compiler/rustc_typeck/src/check/demand.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/compiler/rustc_typeck/src/check/demand.rs b/compiler/rustc_typeck/src/check/demand.rs index bed9d364b91f7..b8209944f00e5 100644 --- a/compiler/rustc_typeck/src/check/demand.rs +++ b/compiler/rustc_typeck/src/check/demand.rs @@ -651,6 +651,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { sp, ) { // For this suggestion to make sense, the type would need to be `Copy`. + let expr_span = self.tcx.hir().span(expr.hir_id); if let Ok(code) = sm.span_to_snippet(expr_span) { let message = if checked_ty.is_region_ptr() { "consider dereferencing the borrow"