diff --git a/src/librustc_ast_lowering/expr.rs b/src/librustc_ast_lowering/expr.rs index b7894eb145b0a..b34e35c3e0c6c 100644 --- a/src/librustc_ast_lowering/expr.rs +++ b/src/librustc_ast_lowering/expr.rs @@ -9,7 +9,7 @@ use rustc_data_structures::thin_vec::ThinVec; use rustc_errors::struct_span_err; use rustc_hir as hir; use rustc_hir::def::Res; -use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned}; +use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned, DUMMY_SP}; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_target::asm; use std::collections::hash_map::Entry; @@ -203,6 +203,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // Include parens in span, but only if it is a super-span. if e.span.contains(ex.span) { ex.span = e.span; + self.spans[ex.hir_id] = e.span; } // Merge attributes into the inner expression. let mut attrs = e.attrs.clone(); @@ -220,7 +221,7 @@ impl<'hir> LoweringContext<'_, 'hir> { }; hir::Expr { - hir_id: self.lower_node_id(e.id), + hir_id: self.lower_node_id(e.id, e.span), kind, span: e.span, attrs: e.attrs.iter().map(|a| self.lower_attr(a)).collect::>().into(), @@ -473,7 +474,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> { hir::Arm { - hir_id: self.next_id(), + hir_id: self.next_id(arm.span), attrs: self.lower_attrs(&arm.attrs), pat: self.lower_pat(&arm.pat), guard: match arm.guard { @@ -481,7 +482,6 @@ impl<'hir> LoweringContext<'_, 'hir> { _ => None, }, body: self.lower_expr(&arm.body), - span: arm.span, } } @@ -510,7 +510,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 { @@ -526,7 +526,7 @@ impl<'hir> LoweringContext<'_, 'hir> { Ident::with_dummy_span(sym::_task_context), hir::BindingAnnotation::Mutable, ); - let param = hir::Param { attrs: &[], hir_id: self.next_id(), pat, span }; + let param = hir::Param { attrs: &[], hir_id: self.next_id(span), pat }; let params = arena_vec![self; param]; let body_id = self.lower_body(move |this| { @@ -548,7 +548,7 @@ impl<'hir> LoweringContext<'_, 'hir> { Some(hir::Movability::Static), ); let generator = hir::Expr { - hir_id: self.lower_node_id(closure_node_id), + hir_id: self.lower_node_id(closure_node_id, span), kind: generator_kind, span, attrs: ThinVec::new(), @@ -629,7 +629,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // Use of `await` outside of an async context, we cannot use `task_context` here. self.expr_err(span) }; - let pin_ty_id = self.next_id(); + let pin_ty_id = self.next_id(span); let new_unchecked_expr_kind = self.expr_call_std_assoc_fn( pin_ty_id, span, @@ -653,7 +653,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); @@ -841,7 +841,7 @@ impl<'hir> LoweringContext<'_, 'hir> { /// Desugar `..=` into `std::ops::RangeInclusive::new(, )`. fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> { - let id = self.next_id(); + let id = self.next_id(span); let e1 = self.lower_expr_mut(e1); let e2 = self.lower_expr_mut(e2); self.expr_call_std_assoc_fn( @@ -898,7 +898,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) } @@ -907,7 +907,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 } @@ -1304,10 +1304,9 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_field(&mut self, f: &Field) -> hir::Field<'hir> { hir::Field { - hir_id: self.next_id(), + hir_id: self.next_id(f.span), ident: f.ident, expr: self.lower_expr(&f.expr), - span: f.span, is_shorthand: f.is_shorthand, } } @@ -1364,6 +1363,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let mut head = self.lower_expr_mut(head); let desugared_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None); head.span = desugared_span; + self.spans[head.hir_id] = desugared_span; let iter = Ident::with_dummy_span(sym::iter); @@ -1448,7 +1448,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // `[opt_ident]: loop { ... }` let kind = hir::ExprKind::Loop(loop_block, opt_label, hir::LoopSource::ForLoop); let loop_expr = self.arena.alloc(hir::Expr { - hir_id: self.lower_node_id(e.id), + hir_id: self.lower_node_id(e.id, e.span), kind, span: e.span, attrs: ThinVec::new(), @@ -1554,7 +1554,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( @@ -1758,8 +1758,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( @@ -1768,7 +1768,6 @@ impl<'hir> LoweringContext<'_, 'hir> { expr: Some(expr), hir_id, rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated), - span, targeted_by_break: false, }), None, @@ -1788,7 +1787,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( @@ -1797,21 +1797,14 @@ impl<'hir> LoweringContext<'_, 'hir> { kind: hir::ExprKind<'hir>, attrs: AttrVec, ) -> hir::Expr<'hir> { - hir::Expr { hir_id: self.next_id(), kind, span, attrs } + hir::Expr { hir_id: self.next_id(span), kind, span, attrs } } fn field(&mut self, ident: Ident, expr: &'hir hir::Expr<'hir>, span: Span) -> hir::Field<'hir> { - hir::Field { hir_id: self.next_id(), ident, span, expr, is_shorthand: false } + hir::Field { hir_id: self.next_id(span), ident, expr, is_shorthand: false } } fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> { - hir::Arm { - hir_id: self.next_id(), - attrs: &[], - pat, - guard: None, - span: expr.span, - body: expr, - } + hir::Arm { hir_id: self.next_id(expr.span), attrs: &[], pat, guard: None, body: expr } } } diff --git a/src/librustc_ast_lowering/item.rs b/src/librustc_ast_lowering/item.rs index 8cfbd408e22b3..6806f129da19a 100644 --- a/src/librustc_ast_lowering/item.rs +++ b/src/librustc_ast_lowering/item.rs @@ -14,7 +14,7 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::LocalDefId; use rustc_span::source_map::{respan, DesugaringKind}; use rustc_span::symbol::{kw, sym, Ident}; -use rustc_span::Span; +use rustc_span::{Span, DUMMY_SP}; use rustc_target::spec::abi; use log::debug; @@ -35,8 +35,8 @@ impl ItemLowerer<'_, '_, '_> { } impl<'a> Visitor<'a> for ItemLowerer<'a, '_, '_> { - fn visit_mod(&mut self, m: &'a Mod, _s: Span, _attrs: &[Attribute], n: NodeId) { - let hir_id = self.lctx.lower_node_id(n); + fn visit_mod(&mut self, m: &'a Mod, span: Span, _attrs: &[Attribute], n: NodeId) { + let hir_id = self.lctx.lower_node_id(n, span); self.lctx.modules.insert( hir_id, @@ -206,14 +206,13 @@ impl<'hir> LoweringContext<'_, 'hir> { if let ItemKind::MacroDef(MacroDef { ref body, macro_rules }) = i.kind { if !macro_rules || attr::contains_name(&i.attrs, sym::macro_export) { - let hir_id = self.lower_node_id(i.id); + let hir_id = self.lower_node_id(i.id, i.span); let body = P(self.lower_mac_args(body)); self.exported_macros.push(hir::MacroDef { ident, vis, attrs, hir_id, - span: i.span, ast: MacroDef { body, macro_rules }, }); } else { @@ -224,7 +223,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let kind = self.lower_item_kind(i.span, i.id, &mut ident, attrs, &mut vis, &i.kind); - Some(hir::Item { hir_id: self.lower_node_id(i.id), ident, attrs, kind, vis, span: i.span }) + Some(hir::Item { hir_id: self.lower_node_id(i.id, i.span), ident, attrs, kind, vis }) } fn lower_item_kind( @@ -319,14 +318,14 @@ impl<'hir> LoweringContext<'_, 'hir> { self.lower_generics(generics, ImplTraitContext::disallowed()), ), ItemKind::Struct(ref struct_def, ref generics) => { - let struct_def = self.lower_variant_data(struct_def); + let struct_def = self.lower_variant_data(span, struct_def); hir::ItemKind::Struct( struct_def, self.lower_generics(generics, ImplTraitContext::disallowed()), ) } ItemKind::Union(ref vdata, ref generics) => { - let vdata = self.lower_variant_data(vdata); + let vdata = self.lower_variant_data(span, vdata); hir::ItemKind::Union( vdata, self.lower_generics(generics, ImplTraitContext::disallowed()), @@ -357,7 +356,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // method, it will not be considered an in-band // lifetime to be added, but rather a reference to a // parent lifetime. - let lowered_trait_impl_id = self.lower_node_id(id); + let lowered_trait_impl_id = self.lower_node_id(id, DUMMY_SP); let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs( ast_generics, def_id, @@ -499,20 +498,13 @@ 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); let vis = this.rebuild_vis(&vis); - this.insert_item(hir::Item { - hir_id: new_id, - ident, - attrs, - kind, - vis, - span, - }); + this.insert_item(hir::Item { hir_id: new_id, ident, attrs, kind, vis }); }); } @@ -553,7 +545,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(); @@ -574,14 +566,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let kind = this.lower_use_tree(use_tree, &prefix, id, &mut vis, &mut ident, attrs); - this.insert_item(hir::Item { - hir_id: new_hir_id, - ident, - attrs, - kind, - vis, - span: use_tree.span, - }); + this.insert_item(hir::Item { hir_id: new_hir_id, ident, attrs, kind, vis }); }); } @@ -622,7 +607,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, @@ -638,7 +623,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), } } }; @@ -648,7 +633,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem<'hir> { let def_id = self.resolver.definitions().local_def_id(i.id); hir::ForeignItem { - hir_id: self.lower_node_id(i.id), + hir_id: self.lower_node_id(i.id, i.span), ident: i.ident, attrs: self.lower_attrs(&i.attrs), kind: match i.kind { @@ -677,7 +662,6 @@ impl<'hir> LoweringContext<'_, 'hir> { ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"), }, vis: self.lower_visibility(&i.vis, None), - span: i.span, } } @@ -695,15 +679,14 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> { hir::Variant { attrs: self.lower_attrs(&v.attrs), - data: self.lower_variant_data(&v.data), + data: self.lower_variant_data(v.span, &v.data), disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)), - id: self.lower_node_id(v.id), + id: self.lower_node_id(v.id, v.span), ident: v.ident, - span: v.span, } } - fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData<'hir> { + fn lower_variant_data(&mut self, span: Span, vdata: &VariantData) -> hir::VariantData<'hir> { match *vdata { VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct( self.arena @@ -713,9 +696,9 @@ impl<'hir> LoweringContext<'_, 'hir> { VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple( self.arena .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_struct_field(f))), - self.lower_node_id(id), + self.lower_node_id(id, span), ), - VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id)), + VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id, span)), } } @@ -733,8 +716,7 @@ impl<'hir> LoweringContext<'_, 'hir> { self.lower_ty(&f.ty, ImplTraitContext::disallowed()) }; hir::StructField { - span: f.span, - hir_id: self.lower_node_id(f.id), + hir_id: self.lower_node_id(f.id, f.span), ident: match f.ident { Some(ident) => ident, // FIXME(jseyfried): positional field hygiene. @@ -781,12 +763,11 @@ impl<'hir> LoweringContext<'_, 'hir> { }; hir::TraitItem { - hir_id: self.lower_node_id(i.id), + hir_id: self.lower_node_id(i.id, i.span), ident: i.ident, attrs: self.lower_attrs(&i.attrs), generics, kind, - span: i.span, } } @@ -801,9 +782,9 @@ impl<'hir> LoweringContext<'_, 'hir> { } AssocItemKind::MacCall(..) => unimplemented!(), }; - let id = hir::TraitItemId { hir_id: self.lower_node_id(i.id) }; + let id = hir::TraitItemId { hir_id: self.lower_node_id(i.id, i.span) }; let defaultness = hir::Defaultness::Default { has_value: has_default }; - hir::TraitItemRef { id, ident: i.ident, span: i.span, defaultness, kind } + hir::TraitItemRef { id, ident: i.ident, defaultness, kind } } /// Construct `ExprKind::Err` for the given `span`. @@ -865,14 +846,13 @@ impl<'hir> LoweringContext<'_, 'hir> { let has_value = true; let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value); hir::ImplItem { - hir_id: self.lower_node_id(i.id), + hir_id: self.lower_node_id(i.id, i.span), ident: i.ident, attrs: self.lower_attrs(&i.attrs), generics, vis: self.lower_visibility(&i.vis, None), defaultness, kind, - span: i.span, } } @@ -881,9 +861,8 @@ impl<'hir> LoweringContext<'_, 'hir> { let has_value = true; let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value); hir::ImplItemRef { - id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) }, + id: hir::ImplItemId { hir_id: self.lower_node_id(i.id, i.span) }, ident: i.ident, - span: i.span, vis: self.lower_visibility(&i.vis, Some(i.id)), defaultness, kind: match &i.kind { @@ -913,9 +892,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); @@ -970,9 +949,8 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> { hir::Param { attrs: self.lower_attrs(¶m.attrs), - hir_id: self.lower_node_id(param.id), + hir_id: self.lower_node_id(param.id, param.span), pat: self.lower_pat(¶m.pat), - span: param.span, } } @@ -1067,7 +1045,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. @@ -1098,7 +1076,6 @@ impl<'hir> LoweringContext<'_, 'hir> { attrs: parameter.attrs, hir_id: parameter.hir_id, pat: new_parameter_pat, - span: parameter.span, }; if is_simple_parameter { @@ -1413,7 +1390,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/src/librustc_ast_lowering/lib.rs b/src/librustc_ast_lowering/lib.rs index 335cc3e61040d..3a8a161f127e1 100644 --- a/src/librustc_ast_lowering/lib.rs +++ b/src/librustc_ast_lowering/lib.rs @@ -53,8 +53,8 @@ use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res}; use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX}; use rustc_hir::definitions::{DefKey, DefPathData, Definitions}; use rustc_hir::intravisit; -use rustc_hir::{ConstArg, GenericArg, ParamName}; -use rustc_index::vec::IndexVec; +use rustc_hir::{ConstArg, GenericArg, HirIdVec, ParamName}; +use rustc_index::vec::{Idx, IndexVec}; use rustc_session::config::nightly_options; use rustc_session::lint::{builtin::BARE_TRAIT_OBJECTS, BuiltinLintDiagnostics, LintBuffer}; use rustc_session::parse::ParseSess; @@ -62,7 +62,7 @@ use rustc_session::Session; use rustc_span::hygiene::ExpnId; use rustc_span::source_map::{respan, DesugaringKind, ExpnData, ExpnKind}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::Span; +use rustc_span::{Span, DUMMY_SP}; use log::{debug, trace}; use smallvec::{smallvec, SmallVec}; @@ -114,6 +114,9 @@ struct LoweringContext<'a, 'hir: 'a> { modules: BTreeMap, + /// Collected spans from the AST. + spans: HirIdVec, + generator_kind: Option, /// When inside an `async` context, this is the `HirId` of the @@ -304,6 +307,7 @@ pub fn lower_crate<'a, 'hir>( bodies: BTreeMap::new(), trait_impls: BTreeMap::new(), modules: BTreeMap::new(), + spans: Default::default(), exported_macros: Vec::new(), non_exported_macro_attrs: Vec::new(), catch_scopes: Vec::new(), @@ -473,7 +477,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { if let PatKind::Paren(..) | PatKind::Rest = p.kind { // Doesn't generate a HIR node } else if let Some(owner) = self.hir_id_owner { - self.lctx.lower_node_id_with_owner(p.id, owner); + self.lctx.lower_node_id_with_owner(p.id, owner, p.span); } visit::walk_pat(self, p) @@ -545,7 +549,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, hir_id_owner: None }, c); @@ -566,8 +570,12 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.resolver.definitions().init_node_id_to_hir_id_mapping(self.node_id_to_hir_id); + //FIXME(cjgillot) Ideally, each LocalDefId would be a HIR owner. + // In the mean time, allocate the missing empty vectors. + self.spans.push_owner(Idx::new(self.resolver.definitions().def_index_count() - 1)); + hir::Crate { - item: hir::CrateItem { module, attrs, span: c.span }, + item: hir::CrateItem { module, attrs }, exported_macros: self.arena.alloc_from_iter(self.exported_macros), non_exported_macro_attrs: self.arena.alloc_from_iter(self.non_exported_macro_attrs), items: self.items, @@ -579,6 +587,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { modules: self.modules, proc_macros, trait_map, + spans: self.spans, } } @@ -594,7 +603,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 } @@ -602,6 +611,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); @@ -612,15 +622,26 @@ 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. + debug_assert!( + self.spans[existing_hir_id] == DUMMY_SP || 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 { @@ -647,8 +668,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; @@ -657,8 +678,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) @@ -680,14 +706,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); }) }) @@ -809,11 +835,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ); hir::GenericParam { - hir_id: self.lower_node_id(node_id), + hir_id: self.lower_node_id(node_id, span), name: hir_name, attrs: &[], bounds: &[], - span, pure_wrt_drop: false, kind: hir::GenericParamKind::Lifetime { kind }, } @@ -1120,10 +1145,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }; hir::TypeBinding { - hir_id: self.lower_node_id(constraint.id), + hir_id: self.lower_node_id(constraint.id, constraint.span), ident: constraint.ident, kind, - span: constraint.span, } } @@ -1170,20 +1194,19 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { tokens: None, }; - let ct = self.with_new_scopes(|this| hir::AnonConst { - hir_id: this.lower_node_id(node_id), - body: this.lower_const_body(path_expr.span, Some(&path_expr)), + let ct = self.lower_anon_const(&AnonConst { + id: node_id, + value: rustc_ast::ptr::P(path_expr), }); - return GenericArg::Const(ConstArg { value: ct, span: ty.span }); + return GenericArg::Const(ConstArg { value: ct }); } } } GenericArg::Type(self.lower_ty_direct(&ty, itctx)) } - ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg { - value: self.lower_anon_const(&ct), - span: ct.value.span, - }), + ast::GenericArg::Const(ct) => { + GenericArg::Const(ConstArg { value: self.lower_anon_const(&ct) }) + } } } @@ -1199,7 +1222,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 { @@ -1209,7 +1232,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> { @@ -1348,12 +1371,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Set the name to `impl Bound1 + Bound2`. let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span); in_band_ty_params.push(hir::GenericParam { - hir_id: self.lower_node_id(def_node_id), + hir_id: self.lower_node_id(def_node_id, span), name: ParamName::Plain(ident), pure_wrt_drop: false, attrs: &[], bounds: hir_bounds, - span, kind: hir::GenericParamKind::Type { default: None, synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), @@ -1404,7 +1426,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( @@ -1476,7 +1498,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { opaque_ty_span: Span, ) -> hir::HirId { let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item); - let opaque_ty_id = self.lower_node_id(opaque_ty_node_id); + let opaque_ty_id = self.lower_node_id(opaque_ty_node_id, opaque_ty_span); // Generate an `type Foo = impl Trait;` declaration. trace!("registering opaque type with id {:#?}", opaque_ty_id); let opaque_ty_item = hir::Item { @@ -1485,7 +1507,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { attrs: Default::default(), 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 @@ -1531,15 +1552,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); } } @@ -1612,14 +1633,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.definitions().create_def_with_parent( self.parent, def_node_id, @@ -1642,7 +1666,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.output_lifetime_params.push(hir::GenericParam { hir_id, name, - span: lifetime.span, pure_wrt_drop: false, attrs: &[], bounds: &[], @@ -1703,11 +1726,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let init = l.init.as_ref().map(|e| self.lower_expr(e)); ( hir::Local { - hir_id: self.lower_node_id(l.id), + hir_id: self.lower_node_id(l.id, l.span), ty, pat: self.lower_pat(&l.pat), init, - span: l.span, attrs: l.attrs.clone(), source: hir::LocalSource::Normal, }, @@ -2000,7 +2022,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { .map(|&(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), }) @@ -2009,7 +2031,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, }))); @@ -2059,7 +2081,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { hir::GenericBound::Trait( hir::PolyTraitRef { - trait_ref: hir::TraitRef { path: future_path, hir_ref_id: self.next_id() }, + trait_ref: hir::TraitRef { path: future_path, hir_ref_id: self.next_id(span) }, bound_generic_params: &[], span, }, @@ -2115,7 +2137,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>( @@ -2217,9 +2239,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }; hir::GenericParam { - hir_id: self.lower_node_id(param.id), + hir_id: self.lower_node_id(param.id, param.ident.span), name, - span: param.ident.span, pure_wrt_drop: attr::contains_name(¶m.attrs, sym::may_dangle), attrs: self.lower_attrs(¶m.attrs), bounds: self.arena.alloc_from_iter(bounds), @@ -2236,7 +2257,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( @@ -2317,11 +2338,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } hir::Block { - hir_id: self.lower_node_id(b.id), + hir_id: self.lower_node_id(b.id, b.span), stmts: self.arena.alloc_from_iter(stmts), expr, rules: self.lower_block_check_mode(&b.rules), - span: b.span, targeted_by_break, } } @@ -2334,9 +2354,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 } }) } @@ -2347,15 +2368,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let mut ids: SmallVec<[hir::Stmt<'hir>; 1]> = item_ids .into_iter() .map(|item_id| { - let item_id = hir::ItemId { id: self.lower_node_id(item_id) }; + let item_id = hir::ItemId { id: self.lower_node_id(item_id, DUMMY_SP) }; self.stmt(s.span, hir::StmtKind::Item(item_id)) }) .collect(); ids.push({ hir::Stmt { - hir_id: self.lower_node_id(s.id), + hir_id: self.lower_node_id(s.id, s.span), kind: hir::StmtKind::Local(self.arena.alloc(l)), - span: s.span, } }); return ids; @@ -2369,10 +2389,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { .map(|item_id| { let hir_id = id .take() - .map(|id| self.lower_node_id(id)) - .unwrap_or_else(|| self.next_id()); + .map(|id| self.lower_node_id(id, s.span)) + .unwrap_or_else(|| self.next_id(s.span)); - hir::Stmt { hir_id, kind: hir::StmtKind::Item(item_id), span: s.span } + hir::Stmt { hir_id, kind: hir::StmtKind::Item(item_id) } }) .collect(); } @@ -2381,7 +2401,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { StmtKind::Empty => return smallvec![], StmtKind::MacCall(..) => panic!("shouldn't exist here"), }; - smallvec![hir::Stmt { hir_id: self.lower_node_id(s.id), kind, span: s.span }] + smallvec![hir::Stmt { hir_id: self.lower_node_id(s.id, s.span), kind }] } fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode { @@ -2416,7 +2436,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Helper methods for building HIR. fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> { - hir::Stmt { span, kind, hir_id: self.next_id() } + hir::Stmt { kind, hir_id: self.next_id(span) } } fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> { @@ -2431,7 +2451,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { pat: &'hir hir::Pat<'hir>, source: hir::LocalSource, ) -> hir::Stmt<'hir> { - let local = hir::Local { attrs, hir_id: self.next_id(), init, pat, source, span, ty: None }; + let local = hir::Local { attrs, hir_id: self.next_id(span), init, pat, source, ty: None }; self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local))) } @@ -2448,9 +2468,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let blk = hir::Block { stmts, expr, - hir_id: self.next_id(), + hir_id: self.next_id(span), rules: hir::BlockCheckMode::DefaultBlock, - span, targeted_by_break: false, }; self.arena.alloc(blk) @@ -2504,13 +2523,12 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ident: Ident, bm: hir::BindingAnnotation, ) -> (&'hir hir::Pat<'hir>, hir::HirId) { - let hir_id = self.next_id(); + let hir_id = self.next_id(span); ( self.arena.alloc(hir::Pat { hir_id, kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None), - span, }), hir_id, ) @@ -2521,7 +2539,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(), kind, span }) + self.arena.alloc(hir::Pat { hir_id: self.next_id(span), kind }) } /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when @@ -2544,7 +2562,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let res = self.expect_full_res(segment.id); hir::PathSegment { ident: segment.ident, - hir_id: Some(self.lower_node_id(segment.id)), + hir_id: Some(self.lower_node_id(segment.id, segment.ident.span)), res: Some(self.lower_res(res)), infer_args: true, args: None, @@ -2579,7 +2597,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), @@ -2605,7 +2623,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), } @@ -2700,7 +2718,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, }; @@ -2709,7 +2727,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/src/librustc_ast_lowering/pat.rs b/src/librustc_ast_lowering/pat.rs index 55c1f80266337..94506b70fe817 100644 --- a/src/librustc_ast_lowering/pat.rs +++ b/src/librustc_ast_lowering/pat.rs @@ -54,11 +54,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ); let fs = self.arena.alloc_from_iter(fields.iter().map(|f| hir::FieldPat { - hir_id: self.next_id(), + hir_id: self.next_id(f.span), ident: f.ident, pat: self.lower_pat(&f.pat), is_shorthand: f.is_shorthand, - span: f.span, })); hir::PatKind::Struct(qpath, fs, etc) } @@ -236,7 +235,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), ) @@ -267,7 +266,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), kind, span: p.span }) + self.arena.alloc(hir::Pat { hir_id: self.lower_node_id(p.id, p.span), kind }) } /// Emit a friendly error for extra `..` patterns in a tuple/tuple struct/slice pattern. diff --git a/src/librustc_ast_lowering/path.rs b/src/librustc_ast_lowering/path.rs index e5ce51f8d2d1f..4f1bcd4a1ea95 100644 --- a/src/librustc_ast_lowering/path.rs +++ b/src/librustc_ast_lowering/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)); } @@ -268,10 +268,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }); let first_generic_span = generic_args .args - .iter() - .map(|a| a.span()) - .chain(generic_args.bindings.iter().map(|b| b.span)) - .next(); + .first() + .map(|a| self.spans[a.id()]) + .or_else(|| generic_args.bindings.first().map(|b| self.spans[b.hir_id])); if !generic_args.parenthesized && !has_lifetimes { generic_args.args = self .elided_path_lifetimes( @@ -342,9 +341,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={:?}", @@ -428,6 +427,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ) -> hir::TypeBinding<'hir> { let ident = Ident::with_dummy_span(hir::FN_OUTPUT_NAME); let kind = hir::TypeBindingKind::Equality { ty }; - hir::TypeBinding { hir_id: self.next_id(), span, ident, kind } + hir::TypeBinding { hir_id: self.next_id(span), ident, kind } } } diff --git a/src/librustc_codegen_llvm/consts.rs b/src/librustc_codegen_llvm/consts.rs index 9d9b53fc4a87c..d1d0d54cd4c79 100644 --- a/src/librustc_codegen_llvm/consts.rs +++ b/src/librustc_codegen_llvm/consts.rs @@ -214,10 +214,13 @@ impl CodegenCx<'ll, 'tcx> { let llty = self.layout_of(ty).llvm_type(self); // FIXME: refactor this to work without accessing the HIR let (g, attrs) = match self.tcx.hir().get(id) { - Node::Item(&hir::Item { attrs, span, kind: hir::ItemKind::Static(..), .. }) => { + Node::Item(&hir::Item { + attrs, hir_id, kind: hir::ItemKind::Static(..), .. + }) => { let sym_str = sym.as_str(); if let Some(g) = self.get_declared_value(&sym_str) { if self.val_ty(g) != self.type_ptr_to(llty) { + let span = self.tcx.hir().span(hir_id); span_bug!(span, "Conflicting types for static"); } } @@ -235,11 +238,12 @@ impl CodegenCx<'ll, 'tcx> { Node::ForeignItem(&hir::ForeignItem { ref attrs, - span, + hir_id, kind: hir::ForeignItemKind::Static(..), .. }) => { let fn_attrs = self.tcx.codegen_fn_attrs(def_id); + let span = self.tcx.hir().span(hir_id); (check_and_apply_linkage(&self, &fn_attrs, ty, sym, span), &**attrs) } diff --git a/src/librustc_codegen_ssa/mono_item.rs b/src/librustc_codegen_ssa/mono_item.rs index 5994ef2be5467..fe74b1769acea 100644 --- a/src/librustc_codegen_ssa/mono_item.rs +++ b/src/librustc_codegen_ssa/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 span = cx.tcx().hir().span(hir_id); + span_bug!(span, "Mismatch between hir::Item type and MonoItem type") } } MonoItem::Fn(instance) => { diff --git a/src/librustc_hir/hir.rs b/src/librustc_hir/hir.rs index 7d1cb7738c35e..dd9dc2b599f94 100644 --- a/src/librustc_hir/hir.rs +++ b/src/librustc_hir/hir.rs @@ -1,6 +1,7 @@ use crate::def::{DefKind, Namespace, Res}; use crate::def_id::DefId; crate use crate::hir_id::HirId; +use crate::hir_id::HirIdVec; use crate::itemlikevisit; use rustc_ast::ast::{self, CrateSugar, LlvmAsmDialect}; @@ -15,7 +16,7 @@ use rustc_macros::HashStable_Generic; use rustc_span::def_id::LocalDefId; use rustc_span::source_map::{SourceMap, Spanned}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{MultiSpan, Span, DUMMY_SP}; +use rustc_span::{Span, DUMMY_SP}; use rustc_target::asm::InlineAsmRegOrRegClass; use rustc_target::spec::abi::Abi; @@ -245,7 +246,6 @@ impl<'hir> PathSegment<'hir> { #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub struct ConstArg { pub value: AnonConst, - pub span: Span, } #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] @@ -256,14 +256,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, @@ -424,7 +416,6 @@ pub struct GenericParam<'hir> { pub name: ParamName, pub attrs: &'hir [Attribute], pub bounds: GenericBounds<'hir>, - pub span: Span, pub pure_wrt_drop: bool, pub kind: GenericParamKind<'hir>, } @@ -489,14 +480,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 @@ -598,7 +581,6 @@ pub struct ModuleItems { pub struct CrateItem<'hir> { pub module: Mod<'hir>, pub attrs: &'hir [Attribute], - pub span: Span, } /// The top-level data structure that stores the entire contents of @@ -641,6 +623,9 @@ pub struct Crate<'hir> { pub proc_macros: Vec, pub trait_map: BTreeMap>, + + /// Collected spans from the AST. + pub spans: HirIdVec, } impl Crate<'hir> { @@ -721,7 +706,6 @@ pub struct MacroDef<'hir> { pub vis: Visibility<'hir>, pub attrs: &'hir [Attribute], pub hir_id: HirId, - pub span: Span, pub ast: ast::MacroDef, } @@ -739,7 +723,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. @@ -751,7 +734,6 @@ pub struct Pat<'hir> { #[stable_hasher(ignore)] pub hir_id: HirId, pub kind: PatKind<'hir>, - pub span: Span, } impl Pat<'_> { @@ -834,7 +816,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 @@ -1099,7 +1080,6 @@ impl UnOp { pub struct Stmt<'hir> { pub hir_id: HirId, pub kind: StmtKind<'hir>, - pub span: Span, } /// The contents of a statement. @@ -1137,7 +1117,6 @@ pub struct Local<'hir> { /// Initializer expression to set the value, if any. pub init: Option<&'hir Expr<'hir>>, pub hir_id: HirId, - pub span: Span, pub attrs: AttrVec, /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop /// desugaring. Otherwise will be `Normal`. @@ -1150,7 +1129,6 @@ pub struct Local<'hir> { pub struct Arm<'hir> { #[stable_hasher(ignore)] pub hir_id: HirId, - pub span: Span, pub attrs: &'hir [Attribute], /// If this pattern and the optional guard matches, then `body` is evaluated. pub pat: &'hir Pat<'hir>, @@ -1171,7 +1149,6 @@ pub struct Field<'hir> { pub hir_id: HirId, pub ident: Ident, pub expr: &'hir Expr<'hir>, - pub span: Span, pub is_shorthand: bool, } @@ -1868,7 +1845,6 @@ pub struct TraitItem<'hir> { pub attrs: &'hir [Attribute], pub generics: Generics<'hir>, pub kind: TraitItemKind<'hir>, - pub span: Span, } /// Represents a trait method's body (or just argument names). @@ -1911,7 +1887,6 @@ pub struct ImplItem<'hir> { pub attrs: &'hir [Attribute], pub generics: Generics<'hir>, pub kind: ImplItemKind<'hir>, - pub span: Span, } /// Represents various kinds of content within an `impl`. @@ -1959,7 +1934,6 @@ pub struct TypeBinding<'hir> { #[stable_hasher(project(name))] pub ident: Ident, pub kind: TypeBindingKind<'hir>, - pub span: Span, } // Represents the two kinds of type bindings. @@ -2154,7 +2128,6 @@ pub struct Param<'hir> { pub attrs: &'hir [Attribute], pub hir_id: HirId, pub pat: &'hir Pat<'hir>, - pub span: Span, } /// Represents the header (not the body) of a function declaration. @@ -2288,8 +2261,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, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] @@ -2381,7 +2352,6 @@ impl VisibilityKind<'_> { #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub struct StructField<'hir> { - pub span: Span, #[stable_hasher(project(name))] pub ident: Ident, pub vis: Visibility<'hir>, @@ -2451,7 +2421,6 @@ pub struct Item<'hir> { pub attrs: &'hir [Attribute], pub kind: ItemKind<'hir>, pub vis: Visibility<'hir>, - pub span: Span, } #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] @@ -2591,7 +2560,6 @@ pub struct TraitItemRef { #[stable_hasher(project(name))] pub ident: Ident, pub kind: AssocItemKind, - pub span: Span, pub defaultness: Defaultness, } @@ -2607,7 +2575,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, } @@ -2626,7 +2593,6 @@ pub struct ForeignItem<'hir> { pub attrs: &'hir [Attribute], pub kind: ForeignItemKind<'hir>, pub hir_id: HirId, - pub span: Span, pub vis: Visibility<'hir>, } diff --git a/src/librustc_hir/hir_id.rs b/src/librustc_hir/hir_id.rs index d782c3dd70a2c..bffdcee424d76 100644 --- a/src/librustc_hir/hir_id.rs +++ b/src/librustc_hir/hir_id.rs @@ -1,4 +1,5 @@ use crate::def_id::{LocalDefId, CRATE_DEF_INDEX}; +use rustc_index::vec::IndexVec; use std::fmt; /// Uniquely identifies a node in the HIR of the current crate. It is @@ -46,3 +47,45 @@ pub const CRATE_HIR_ID: HirId = HirId { }; pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX; + +#[derive(Clone, Default, Debug, RustcEncodable, RustcDecodable)] +pub struct HirIdVec { + map: IndexVec>, +} + +impl HirIdVec { + pub fn push_owner(&mut self, id: LocalDefId) { + self.map.ensure_contains_elem(id, IndexVec::new); + } + + pub fn push(&mut self, id: HirId, value: T) { + if id.local_id == ItemLocalId::from_u32(0) { + self.push_owner(id.owner); + } + let submap = &mut self.map[id.owner]; + let _ret_id = submap.push(value); + debug_assert_eq!(_ret_id, id.local_id); + } + + pub fn get(&self, id: HirId) -> Option<&T> { + self.map.get(id.owner)?.get(id.local_id) + } + + pub fn get_owner(&self, id: LocalDefId) -> &IndexVec { + &self.map[id] + } +} + +impl std::ops::Index for HirIdVec { + type Output = T; + + fn index(&self, id: HirId) -> &T { + &self.map[id.owner][id.local_id] + } +} + +impl std::ops::IndexMut for HirIdVec { + fn index_mut(&mut self, id: HirId) -> &mut T { + &mut self.map[id.owner][id.local_id] + } +} diff --git a/src/librustc_hir/intravisit.rs b/src/librustc_hir/intravisit.rs index 23d642731da4d..2f87f222a4d72 100644 --- a/src/librustc_hir/intravisit.rs +++ b/src/librustc_hir/intravisit.rs @@ -37,7 +37,6 @@ use crate::itemlikevisit::{ItemLikeVisitor, ParItemLikeVisitor}; use rustc_ast::ast::{Attribute, Label}; use rustc_ast::walk_list; use rustc_span::symbol::{Ident, Symbol}; -use rustc_span::Span; pub struct DeepVisitor<'v, V> { visitor: &'v mut V, @@ -318,13 +317,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>) { @@ -366,8 +365,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) @@ -399,7 +398,6 @@ pub trait Visitor<'v>: Sized { _: Symbol, _: &'v Generics<'v>, _parent_id: HirId, - _: Span, ) { walk_struct_def(self, s) } @@ -411,7 +409,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) } @@ -431,17 +428,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) @@ -463,7 +460,7 @@ pub trait Visitor<'v>: Sized { /// Walks the contents of a crate. See also `Crate::visit_all_items`. pub fn walk_crate<'v, V: Visitor<'v>>(visitor: &mut V, krate: &'v Crate<'v>) { - visitor.visit_mod(&krate.item.module, krate.item.span, CRATE_HIR_ID); + visitor.visit_mod(&krate.item.module, CRATE_HIR_ID); walk_list!(visitor, visit_attribute, krate.item.attrs); walk_list!(visitor, visit_macro_def, krate.exported_macros); } @@ -497,7 +494,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) { @@ -547,7 +544,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, _) => { @@ -562,12 +559,11 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) { FnKind::ItemFn(item.ident, generics, sig.header, &item.vis, &item.attrs), &sig.decl, body_id, - item.span, item.hir_id, ), ItemKind::Mod(ref module) => { // `visit_mod()` takes care of visiting the `Item`'s `HirId`. - visitor.visit_mod(module, item.span, item.hir_id) + visitor.visit_mod(module, item.hir_id) } ItemKind::ForeignMod(ref foreign_module) => { visitor.visit_id(item.hir_id); @@ -589,7 +585,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) { ItemKind::Enum(ref enum_definition, ref generics) => { visitor.visit_generics(generics); // `visit_enum_def()` takes care of visiting the `Item`'s `HirId`. - visitor.visit_enum_def(enum_definition, generics, item.hir_id, item.span) + visitor.visit_enum_def(enum_definition, generics, item.hir_id) } ItemKind::Impl { unsafety: _, @@ -612,13 +608,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); @@ -658,13 +648,7 @@ pub fn walk_variant<'v, V: Visitor<'v>>( ) { visitor.visit_ident(variant.ident); visitor.visit_id(variant.id); - visitor.visit_variant_data( - &variant.data, - variant.ident.name, - generics, - parent_item_id, - variant.span, - ); + visitor.visit_variant_data(&variant.data, variant.ident.name, generics, parent_item_id); walk_list!(visitor, visit_anon_const, &variant.disr_expr); walk_list!(visitor, visit_attribute, variant.attrs); } @@ -688,7 +672,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); @@ -709,12 +693,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); @@ -722,34 +701,26 @@ 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); } } } 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); } @@ -774,14 +745,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); @@ -918,7 +889,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); @@ -949,7 +919,6 @@ pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v Trai FnKind::Method(trait_item.ident, sig, None, &trait_item.attrs), &sig.decl, body_id, - trait_item.span, trait_item.hir_id, ); } @@ -963,7 +932,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); @@ -972,16 +941,8 @@ 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 { - hir_id: _, - ident, - ref vis, - ref defaultness, - attrs, - ref generics, - ref kind, - span: _, - } = *impl_item; + let ImplItem { hir_id: _, ident, ref vis, ref defaultness, attrs, ref generics, ref kind } = + *impl_item; visitor.visit_ident(ident); visitor.visit_vis(vis); @@ -999,7 +960,6 @@ pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplIt FnKind::Method(impl_item.ident, sig, Some(&impl_item.vis), &impl_item.attrs), &sig.decl, body_id, - impl_item.span, impl_item.hir_id, ); } @@ -1012,7 +972,7 @@ pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplIt 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); @@ -1071,7 +1031,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); @@ -1087,7 +1047,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) => { @@ -1117,7 +1077,6 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>) FnKind::Closure(&expression.attrs), function_declaration, body, - expression.span, expression.hir_id, ), ExprKind::Block(ref block, ref opt_label) => { @@ -1141,7 +1100,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/src/librustc_hir/pat_util.rs b/src/librustc_hir/pat_util.rs index 2f1b5da8e13a0..cb67626b3a670 100644 --- a/src/librustc_hir/pat_util.rs +++ b/src/librustc_hir/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}; @@ -79,10 +78,10 @@ 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); } }); } @@ -91,17 +90,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, @@ -181,7 +177,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/src/librustc_hir/stable_hash_impls.rs b/src/librustc_hir/stable_hash_impls.rs index 1d3f44a08993a..264ef5bedadca 100644 --- a/src/librustc_hir/stable_hash_impls.rs +++ b/src/librustc_hir/stable_hash_impls.rs @@ -115,30 +115,21 @@ impl HashStable for VisibilityKind<'_> impl HashStable for TraitItem<'_> { fn hash_stable(&self, hcx: &mut HirCtx, hasher: &mut StableHasher) { - let TraitItem { hir_id: _, ident, ref attrs, ref generics, ref kind, span } = *self; + let TraitItem { hir_id: _, ident, ref attrs, ref generics, ref kind } = *self; hcx.hash_hir_item_like(|hcx| { ident.name.hash_stable(hcx, hasher); attrs.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 { - hir_id: _, - ident, - ref vis, - defaultness, - ref attrs, - ref generics, - ref kind, - span, - } = *self; + let ImplItem { hir_id: _, ident, ref vis, defaultness, ref attrs, ref generics, ref kind } = + *self; hcx.hash_hir_item_like(|hcx| { ident.name.hash_stable(hcx, hasher); @@ -147,21 +138,19 @@ impl HashStable for ImplItem<'_> { attrs.hash_stable(hcx, hasher); generics.hash_stable(hcx, hasher); kind.hash_stable(hcx, hasher); - span.hash_stable(hcx, hasher); }); } } impl HashStable for Item<'_> { fn hash_stable(&self, hcx: &mut HirCtx, hasher: &mut StableHasher) { - let Item { ident, ref attrs, hir_id: _, ref kind, ref vis, span } = *self; + let Item { ident, ref attrs, hir_id: _, ref kind, ref vis } = *self; hcx.hash_hir_item_like(|hcx| { ident.name.hash_stable(hcx, hasher); attrs.hash_stable(hcx, hasher); kind.hash_stable(hcx, hasher); vis.hash_stable(hcx, hasher); - span.hash_stable(hcx, hasher); }); } } diff --git a/src/librustc_hir_pretty/lib.rs b/src/librustc_hir_pretty/lib.rs index c16b7c63e3147..a498635243c98 100644 --- a/src/librustc_hir_pretty/lib.rs +++ b/src/librustc_hir_pretty/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}; @@ -86,6 +86,7 @@ pub struct State<'a> { pub s: pp::Printer, comments: Option>, ann: &'a (dyn PpAnn + 'a), + spans: &'a HirIdVec, } impl<'a> State<'a> { @@ -166,7 +167,7 @@ pub fn print_crate<'a>( input: String, ann: &'a dyn PpAnn, ) -> String { - let mut s = State::new_from_input(sm, filename, input, ann); + let mut s = State::new_from_input(sm, filename, input, ann, &krate.spans); // When printing the AST, we sometimes need to inject `#[no_std]` here. // Since you can't compile the HIR, it's not necessary. @@ -182,8 +183,18 @@ impl<'a> State<'a> { filename: FileName, input: String, ann: &'a dyn PpAnn, + spans: &'a HirIdVec, ) -> State<'a> { - State { s: pp::mk_printer(), comments: Some(Comments::new(sm, filename, input)), ann } + State { + s: pp::mk_printer(), + comments: Some(Comments::new(sm, filename, input)), + ann, + spans, + } + } + + fn span(&self, hir_id: hir::HirId) -> rustc_span::Span { + self.spans.get(hir_id).copied().unwrap_or(rustc_span::DUMMY_SP) } } @@ -191,7 +202,8 @@ pub fn to_string(ann: &dyn PpAnn, f: F) -> String where F: FnOnce(&mut State<'_>), { - let mut printer = State { s: pp::mk_printer(), comments: None, ann }; + let spans = &HirIdVec::default(); + let mut printer = State { s: pp::mk_printer(), comments: None, ann, spans }; f(&mut printer); printer.s.eof() } @@ -325,18 +337,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(); } } @@ -344,7 +359,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]) { @@ -451,8 +466,9 @@ impl<'a> State<'a> { } pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) { + let item_span = self.span(item.hir_id); self.hardbreak_if_not_bol(); - self.maybe_print_comment(item.span.lo()); + self.maybe_print_comment(item_span.lo()); self.print_outer_attributes(&item.attrs); match item.kind { hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => { @@ -559,8 +575,9 @@ impl<'a> State<'a> { /// Pretty-print an item pub fn print_item(&mut self, item: &hir::Item<'_>) { + let span = self.span(item.hir_id); self.hardbreak_if_not_bol(); - self.maybe_print_comment(item.span.lo()); + self.maybe_print_comment(span.lo()); self.print_outer_attributes(&item.attrs); self.ann.pre(self, AnnNode::Item(item)); match item.kind { @@ -647,14 +664,14 @@ impl<'a> State<'a> { self.nbsp(); self.bopen(); self.print_mod(_mod, &item.attrs); - self.bclose(item.span); + self.bclose(span); } hir::ItemKind::ForeignMod(ref nmod) => { self.head("extern"); self.word_nbsp(nmod.abi.to_string()); self.bopen(); self.print_foreign_mod(nmod, &item.attrs); - self.bclose(item.span); + self.bclose(span); } hir::ItemKind::GlobalAsm(ref ga) => { self.head(visibility_qualified(&item.vis, "global asm")); @@ -683,15 +700,15 @@ 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, span, &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, span, 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, span, true); } hir::ItemKind::Impl { unsafety, @@ -738,7 +755,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(span); } hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => { self.head(""); @@ -765,7 +782,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(span); } hir::ItemKind::TraitAlias(ref generics, ref bounds) => { self.head(""); @@ -829,14 +846,15 @@ impl<'a> State<'a> { pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) { self.bopen(); for v in variants { + let span = self.span(v.id); self.space_if_not_bol(); - self.maybe_print_comment(v.span.lo()); + self.maybe_print_comment(span.lo()); self.print_outer_attributes(&v.attrs); self.ibox(INDENT_UNIT); self.print_variant(v); self.s.word(","); self.end(); - self.maybe_print_trailing_comment(v.span, None); + self.maybe_print_trailing_comment(span, None); } self.bclose(span) } @@ -884,7 +902,8 @@ impl<'a> State<'a> { if let hir::VariantData::Tuple(..) = struct_def { self.popen(); self.commasep(Inconsistent, struct_def.fields(), |s, field| { - s.maybe_print_comment(field.span.lo()); + let span = s.span(field.hir_id); + s.maybe_print_comment(span.lo()); s.print_outer_attributes(&field.attrs); s.print_visibility(&field.vis); s.print_type(&field.ty) @@ -905,8 +924,9 @@ impl<'a> State<'a> { self.hardbreak_if_not_bol(); for field in struct_def.fields() { + let span = self.span(field.hir_id); self.hardbreak_if_not_bol(); - self.maybe_print_comment(field.span.lo()); + self.maybe_print_comment(span.lo()); self.print_outer_attributes(&field.attrs); self.print_visibility(&field.vis); self.print_ident(field.ident); @@ -923,7 +943,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("="); @@ -943,9 +963,10 @@ impl<'a> State<'a> { } pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) { + let span = self.span(ti.hir_id); 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(span.lo()); self.print_outer_attributes(&ti.attrs); match ti.kind { hir::TraitItemKind::Const(ref ty, default) => { @@ -982,9 +1003,10 @@ impl<'a> State<'a> { } pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) { + let span = self.span(ii.hir_id); 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(span.lo()); self.print_outer_attributes(&ii.attrs); self.print_defaultness(ii.defaultness); @@ -1025,7 +1047,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)); @@ -1044,7 +1067,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<'_>) { @@ -1071,7 +1094,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(); @@ -1083,9 +1107,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)) } @@ -1168,7 +1192,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) => { @@ -1810,7 +1834,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 @@ -1874,7 +1899,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/src/librustc_incremental/persist/dirty_clean.rs b/src/librustc_incremental/persist/dirty_clean.rs index 2ee95174dffe6..87923b1e3092d 100644 --- a/src/librustc_incremental/persist/dirty_clean.rs +++ b/src/librustc_incremental/persist/dirty_clean.rs @@ -431,8 +431,9 @@ impl DirtyCleanVisitor<'tcx> { } } - fn check_item(&mut self, item_id: hir::HirId, item_span: Span) { + fn check_item(&mut self, item_id: hir::HirId) { let def_id = self.tcx.hir().local_def_id(item_id); + let item_span = self.tcx.hir().span(item_id); for attr in self.tcx.get_attrs(def_id.to_def_id()).iter() { let assertion = match self.assertion_maybe(item_id, attr) { Some(a) => a, @@ -451,15 +452,15 @@ impl DirtyCleanVisitor<'tcx> { impl ItemLikeVisitor<'tcx> for DirtyCleanVisitor<'tcx> { fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { - self.check_item(item.hir_id, item.span); + self.check_item(item.hir_id); } fn visit_trait_item(&mut self, item: &hir::TraitItem<'_>) { - self.check_item(item.hir_id, item.span); + self.check_item(item.hir_id); } fn visit_impl_item(&mut self, item: &hir::ImplItem<'_>) { - self.check_item(item.hir_id, item.span); + self.check_item(item.hir_id); } } diff --git a/src/librustc_index/vec.rs b/src/librustc_index/vec.rs index 4dde33283f575..2fd75a55fa013 100644 --- a/src/librustc_index/vec.rs +++ b/src/librustc_index/vec.rs @@ -671,9 +671,7 @@ impl IndexVec { pub fn convert_index_type(self) -> IndexVec { IndexVec { raw: self.raw, _marker: PhantomData } } -} -impl IndexVec { /// Grows the index vector so that it contains an entry for /// `elem`; if that is already true, then has no /// effect. Otherwise, inserts new values as needed by invoking @@ -686,11 +684,6 @@ impl IndexVec { } } - #[inline] - pub fn resize(&mut self, new_len: usize, value: T) { - self.raw.resize(new_len, value) - } - #[inline] pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) { let min_new_len = elem.index() + 1; @@ -698,6 +691,13 @@ impl IndexVec { } } +impl IndexVec { + #[inline] + pub fn resize(&mut self, new_len: usize, value: T) { + self.raw.resize(new_len, value) + } +} + impl IndexVec { #[inline] pub fn binary_search(&self, value: &T) -> Result { diff --git a/src/librustc_infer/infer/error_reporting/mod.rs b/src/librustc_infer/infer/error_reporting/mod.rs index 9cfa11dd7c813..3f49c5db7dbcd 100644 --- a/src/librustc_infer/infer/error_reporting/mod.rs +++ b/src/librustc_infer/infer/error_reporting/mod.rs @@ -158,7 +158,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) } @@ -167,7 +167,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/src/librustc_infer/infer/error_reporting/need_type_info.rs b/src/librustc_infer/infer/error_reporting/need_type_info.rs index 04d941fb8a7c4..747d5d6c8da8a 100644 --- a/src/librustc_infer/infer/error_reporting/need_type_info.rs +++ b/src/librustc_infer/infer/error_reporting/need_type_info.rs @@ -110,7 +110,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FindHirNodeVisitor<'a, 'tcx> { if let (None, Some(ty)) = (self.found_arg_pattern, self.node_ty_contains_target(param.hir_id)) { - if self.target_span.contains(param.pat.span) { + if self.target_span.contains(self.infcx.tcx.hir().span(param.pat.hir_id)) { self.found_arg_pattern = Some(&*param.pat); self.found_node_ty = Some(ty); } @@ -298,7 +298,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) = name_sp { // `span` here lets us point at `sum` instead of the entire right hand side expr: // error[E0282]: type annotations needed @@ -461,12 +461,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() @@ -476,7 +477,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { } else { format!("consider giving this pattern {}", suffix) }; - err.span_label(pattern.span, msg); + err.span_label(pattern_span, msg); } else if let Some(e) = local_visitor.found_method_call { if let ExprKind::MethodCall(segment, ..) = &e.kind { // Suggest specifying type params or point out the return type of the call: diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index b7f728ec60cfd..a5857984c1b21 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -104,10 +104,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: hir::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() }); @@ -126,7 +127,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers { | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { let def_id = cx.tcx.hir().local_def_id(it.hir_id); - self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id)) + self.check_heap_type(cx, it.hir_id, cx.tcx.type_of(def_id)) } _ => (), } @@ -136,7 +137,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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)); + self.check_heap_type(cx, struct_field.hir_id, cx.tcx.type_of(def_id)); } } _ => (), @@ -145,7 +146,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers { fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) { let ty = cx.tables.node_type(e.hir_id); - self.check_heap_type(cx, e.span, ty); + self.check_heap_type(cx, e.hir_id, ty); } } @@ -170,7 +171,8 @@ impl<'a, 'tcx> LateLintPass<'a, '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) @@ -180,7 +182,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns { if cx.tcx.find_field_index(ident, &variant) == Some(cx.tcx.field_index(fieldpat.hir_id, cx.tables)) { - 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 { @@ -195,7 +197,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns { ident.to_string() }; err.span_suggestion( - fieldpat.span, + fieldpat_span, "use shorthand field pattern", ident, Applicability::MachineApplicable, @@ -349,9 +351,8 @@ impl MissingDoc { fn check_missing_docs_attrs( &self, cx: &LateContext<'_, '_>, - id: Option, + id: hir::HirId, attrs: &[ast::Attribute], - sp: Span, article: &'static str, desc: &'static str, ) { @@ -369,7 +370,7 @@ impl MissingDoc { // Only check publicly-visible items, using the result from the privacy pass. // It's an option so the crate root can also use this function (it doesn't // have a `NodeId`). - if let Some(id) = id { + if id != hir::CRATE_HIR_ID { if !cx.access_levels.is_exported(id) { return; } @@ -377,6 +378,7 @@ impl MissingDoc { let has_doc = attrs.iter().any(|a| has_doc(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), @@ -406,14 +408,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { } fn check_crate(&mut self, cx: &LateContext<'_, '_>, krate: &hir::Crate<'_>) { - self.check_missing_docs_attrs(cx, None, &krate.item.attrs, krate.item.span, "the", "crate"); + self.check_missing_docs_attrs(cx, hir::CRATE_HIR_ID, &krate.item.attrs, "the", "crate"); for macro_def in krate.exported_macros { let has_doc = macro_def.attrs.iter().any(|a| has_doc(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(), ); } @@ -464,7 +467,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { let def_id = cx.tcx.hir().local_def_id(it.hir_id); let (article, desc) = cx.tcx.article_and_description(def_id.to_def_id()); - self.check_missing_docs_attrs(cx, Some(it.hir_id), &it.attrs, it.span, article, desc); + self.check_missing_docs_attrs(cx, it.hir_id, &it.attrs, article, desc); } fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, trait_item: &hir::TraitItem<'_>) { @@ -475,14 +478,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { let def_id = cx.tcx.hir().local_def_id(trait_item.hir_id); let (article, desc) = cx.tcx.article_and_description(def_id.to_def_id()); - self.check_missing_docs_attrs( - cx, - Some(trait_item.hir_id), - &trait_item.attrs, - trait_item.span, - article, - desc, - ); + self.check_missing_docs_attrs(cx, trait_item.hir_id, &trait_item.attrs, article, desc); } fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem<'_>) { @@ -493,31 +489,17 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { let def_id = cx.tcx.hir().local_def_id(impl_item.hir_id); let (article, desc) = cx.tcx.article_and_description(def_id.to_def_id()); - self.check_missing_docs_attrs( - cx, - Some(impl_item.hir_id), - &impl_item.attrs, - impl_item.span, - article, - desc, - ); + self.check_missing_docs_attrs(cx, impl_item.hir_id, &impl_item.attrs, article, desc); } fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, sf: &hir::StructField<'_>) { if !sf.is_positional() { - self.check_missing_docs_attrs( - cx, - Some(sf.hir_id), - &sf.attrs, - sf.span, - "a", - "struct field", - ) + self.check_missing_docs_attrs(cx, sf.hir_id, &sf.attrs, "a", "struct field") } } fn check_variant(&mut self, cx: &LateContext<'_, '_>, v: &hir::Variant<'_>) { - self.check_missing_docs_attrs(cx, Some(v.id), &v.attrs, v.span, "a", "variant"); + self.check_missing_docs_attrs(cx, v.id, &v.attrs, "a", "variant"); } } @@ -562,11 +544,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations { return; } let param_env = ty::ParamEnv::empty(); - if ty.is_copy_modulo_regions(cx.tcx, param_env, item.span) { + let span = cx.tcx.hir().span(item.hir_id); + if ty.is_copy_modulo_regions(cx.tcx, param_env, span) { 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, span, |lint| { lint.build( "type could implement `Copy`; consider adding `impl \ Copy`", @@ -621,7 +604,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations { } if !self.impling_types.as_ref().unwrap().contains(&item.hir_id) { - cx.struct_span_lint(MISSING_DEBUG_IMPLEMENTATIONS, item.span, |lint| { + let span = cx.tcx.hir().span(item.hir_id); + cx.struct_span_lint(MISSING_DEBUG_IMPLEMENTATIONS, span, |lint| { lint.build(&format!( "type does not implement `{}`; consider adding `#[derive(Debug)]` \ or a manual implementation", @@ -815,6 +799,7 @@ declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GEN impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems { fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) { + let span = cx.tcx.hir().span(it.hir_id); match it.kind { hir::ItemKind::Fn(.., ref generics, _) => { if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, sym::no_mangle) { @@ -822,7 +807,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems { match param.kind { GenericParamKind::Lifetime { .. } => {} GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { - cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS, it.span, |lint| { + cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS, span, |lint| { lint.build( "functions generic over types or consts must be mangled", ) @@ -846,7 +831,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems { if attr::contains_name(&it.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| { + cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, span, |lint| { let msg = "const items should never be `#[no_mangle]`"; let mut err = lint.build(msg); @@ -855,11 +840,11 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems { .tcx .sess .source_map() - .span_to_snippet(it.span) + .span_to_snippet(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 = span.with_hi(BytePos(span.lo().0 + start + 5)); err.span_suggestion( const_span, "try a static value", @@ -967,12 +952,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; } @@ -1005,7 +990,7 @@ impl UnreachablePub { impl<'a, 'tcx> LateLintPass<'a, '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( @@ -1013,22 +998,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub { 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<'_>) { - self.perform_lint(cx, "field", field.hir_id, &field.vis, field.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); } } @@ -1062,36 +1040,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); } } @@ -1127,7 +1111,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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(); @@ -1140,7 +1124,8 @@ impl<'a, 'tcx> LateLintPass<'a, '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(); @@ -1152,7 +1137,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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(); @@ -1680,8 +1665,9 @@ impl<'a, 'tcx> LateLintPass<'a, '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, )); @@ -2232,11 +2218,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ClashingExternDecl { // 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 = cx.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_DECL, diff --git a/src/librustc_lint/late.rs b/src/librustc_lint/late.rs index c8f827b1f5ced..c51d18ca10281 100644 --- a/src/librustc_lint/late.rs +++ b/src/librustc_lint/late.rs @@ -26,7 +26,6 @@ use rustc_middle::hir::map::Map; use rustc_middle::ty::{self, TyCtxt}; use rustc_session::lint::LintPass; use rustc_span::symbol::Symbol; -use rustc_span::Span; use log::debug; use std::any::Any; @@ -75,10 +74,10 @@ impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> LateContextAndPass<'a, '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]) { @@ -176,7 +175,6 @@ impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> hir_visit::Visitor<'tcx> fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl<'tcx>, body_id: hir::BodyId, - span: Span, id: hir::HirId, ) { // Wrap in tables here, not just in visit_nested_body, @@ -184,9 +182,9 @@ impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> hir_visit::Visitor<'tcx> let old_tables = self.context.tables; self.context.tables = self.context.tcx.body_tables(body_id); 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.tables = old_tables; } @@ -196,7 +194,6 @@ impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> hir_visit::Visitor<'tcx> _: Symbol, _: &'tcx hir::Generics<'tcx>, _: hir::HirId, - _: Span, ) { lint_callback!(self, check_struct_def, s); hir_visit::walk_struct_def(self, s); @@ -228,13 +225,9 @@ impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> hir_visit::Visitor<'tcx> 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); } } @@ -372,8 +365,8 @@ fn late_lint_mod_pass<'tcx, T: for<'a> LateLintPass<'a, '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/src/librustc_lint/lib.rs b/src/librustc_lint/lib.rs index ca2ca3145abc8..de08c8a015658 100644 --- a/src/librustc_lint/lib.rs +++ b/src/librustc_lint/lib.rs @@ -65,7 +65,7 @@ use rustc_session::lint::builtin::{ INTRA_DOC_LINK_RESOLUTION_FAILURE, INVALID_CODEBLOCK_ATTRIBUTE, MISSING_DOC_CODE_EXAMPLES, PRIVATE_DOC_TESTS, }; -use rustc_span::symbol::{Ident, Symbol}; +use rustc_span::symbol::Ident; use rustc_span::Span; use array_into_iter::ArrayIntoIter; diff --git a/src/librustc_lint/nonstandard_style.rs b/src/librustc_lint/nonstandard_style.rs index 052b461039b23..730ee0fd1b6b4 100644 --- a/src/librustc_lint/nonstandard_style.rs +++ b/src/librustc_lint/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)] @@ -249,13 +249,7 @@ impl NonSnakeCase { } impl<'a, 'tcx> LateLintPass<'a, '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; } @@ -312,7 +306,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase { fk: FnKind<'_>, _: &hir::FnDecl<'_>, _: &hir::Body<'_>, - _: Span, id: hir::HirId, ) { match &fk { diff --git a/src/librustc_lint/passes.rs b/src/librustc_lint/passes.rs index 04a398a29ba7b..a210212b528e2 100644 --- a/src/librustc_lint/passes.rs +++ b/src/librustc_lint/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>); @@ -41,13 +40,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/src/librustc_lint/types.rs b/src/librustc_lint/types.rs index a19c9a3557996..447f93c7c3fc2 100644 --- a/src/librustc_lint/types.rs +++ b/src/librustc_lint/types.rs @@ -77,7 +77,9 @@ fn lint_overflowing_range_endpoint<'a, '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. @@ -1077,18 +1079,15 @@ impl<'a, 'tcx> LateLintPass<'a, '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/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index 8196b37391b21..b00f395e187ed 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -47,7 +47,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults { } let ty = cx.tables.expr_ty(&expr); - let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1); + let span = cx.tcx.hir().span(s.hir_id); + 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; @@ -69,7 +70,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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.) @@ -111,7 +112,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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). @@ -255,7 +256,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements { fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt<'_>) { if let hir::StmtKind::Semi(ref 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| { lint.build("path statement with no effect").emit() }); } diff --git a/src/librustc_metadata/rmeta/encoder.rs b/src/librustc_metadata/rmeta/encoder.rs index cdc8b5e90a642..da6281298b4f5 100644 --- a/src/librustc_metadata/rmeta/encoder.rs +++ b/src/librustc_metadata/rmeta/encoder.rs @@ -837,12 +837,13 @@ impl EncodeContext<'tcx> { let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()); let ast_item = tcx.hir().expect_trait_item(hir_id); + let ast_item_span = tcx.hir().span(hir_id); let trait_item = tcx.associated_item(def_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"), }; record!(self.tables.kind[def_id] <- match trait_item.kind { @@ -886,7 +887,7 @@ impl EncodeContext<'tcx> { ty::AssocKind::Type => EntryKind::AssocType(container), }); record!(self.tables.visibility[def_id] <- trait_item.vis); - record!(self.tables.span[def_id] <- ast_item.span); + record!(self.tables.span[def_id] <- ast_item_span); record!(self.tables.attributes[def_id] <- ast_item.attrs); self.encode_ident_span(def_id, ast_item.ident); self.encode_stability(def_id); @@ -926,20 +927,21 @@ impl EncodeContext<'tcx> { let hir_id = self.tcx.hir().as_local_hir_id(def_id.expect_local()); let ast_item = self.tcx.hir().expect_impl_item(hir_id); + let ast_item_span = self.tcx.hir().span(hir_id); let impl_item = self.tcx.associated_item(def_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)") } }; record!(self.tables.kind[def_id] <- 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); EntryKind::AssocConst( container, @@ -968,7 +970,7 @@ impl EncodeContext<'tcx> { ty::AssocKind::Type => EntryKind::AssocType(container) }); record!(self.tables.visibility[def_id] <- impl_item.vis); - record!(self.tables.span[def_id] <- ast_item.span); + record!(self.tables.span[def_id] <- ast_item_span); record!(self.tables.attributes[def_id] <- ast_item.attrs); self.encode_ident_span(def_id, impl_item.ident); self.encode_stability(def_id); @@ -1081,12 +1083,13 @@ impl EncodeContext<'tcx> { debug!("EncodeContext::encode_info_for_item({:?})", def_id); self.encode_ident_span(def_id, item.ident); + let item_span = tcx.hir().span(item.hir_id); record!(self.tables.kind[def_id] <- match item.kind { 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 qualifs = self.tcx.at(item_span).mir_const_qualif(def_id); EntryKind::Const( qualifs, self.encode_rendered_const_for_body(body_id) @@ -1157,7 +1160,7 @@ impl EncodeContext<'tcx> { 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)) + Some(self.tcx.at(item_span).coerce_unsized_info(def_id)) } else { None } @@ -1190,7 +1193,7 @@ impl EncodeContext<'tcx> { }); record!(self.tables.visibility[def_id] <- ty::Visibility::from_hir(&item.vis, item.hir_id, tcx)); - record!(self.tables.span[def_id] <- item.span); + record!(self.tables.span[def_id] <- item_span); record!(self.tables.attributes[def_id] <- item.attrs); // FIXME(eddyb) there should be a nicer way to do this. match item.kind { @@ -1304,9 +1307,10 @@ impl EncodeContext<'tcx> { /// Serialize the text of exported macros fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) { let def_id = self.tcx.hir().local_def_id(macro_def.hir_id).to_def_id(); + let span = self.tcx.hir().span(macro_def.hir_id); record!(self.tables.kind[def_id] <- EntryKind::MacroDef(self.lazy(macro_def.ast.clone()))); record!(self.tables.visibility[def_id] <- ty::Visibility::Public); - record!(self.tables.span[def_id] <- macro_def.span); + record!(self.tables.span[def_id] <- span); record!(self.tables.attributes[def_id] <- macro_def.attrs); self.encode_ident_span(def_id, macro_def.ident); self.encode_stability(def_id); @@ -1529,6 +1533,7 @@ impl EncodeContext<'tcx> { fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) { let tcx = self.tcx; + let nitem_span = tcx.hir().span(nitem.hir_id); debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id); @@ -1551,7 +1556,7 @@ impl EncodeContext<'tcx> { }); record!(self.tables.visibility[def_id] <- ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, self.tcx)); - record!(self.tables.span[def_id] <- nitem.span); + record!(self.tables.span[def_id] <- nitem_span); record!(self.tables.attributes[def_id] <- nitem.attrs); self.encode_ident_span(def_id, nitem.ident); self.encode_stability(def_id); diff --git a/src/librustc_middle/hir/map/blocks.rs b/src/librustc_middle/hir/map/blocks.rs index a2e4372f017ce..005045d669d86 100644 --- a/src/librustc_middle/hir/map/blocks.rs +++ b/src/librustc_middle/hir/map/blocks.rs @@ -17,7 +17,6 @@ use rustc_hir as hir; use rustc_hir::intravisit::FnKind; use rustc_hir::{Expr, FnDecl, Node}; use rustc_span::symbol::Ident; -use rustc_span::Span; /// An FnLikeNode is a Node that is like a fn, in that it has a decl /// and a body (as well as a NodeId, a span, etc). @@ -116,7 +115,6 @@ struct ItemFnParts<'a> { generics: &'a hir::Generics<'a>, body: hir::BodyId, id: hir::HirId, - span: Span, attrs: &'a [Attribute], } @@ -126,19 +124,12 @@ struct ClosureParts<'a> { decl: &'a FnDecl<'a>, body: hir::BodyId, id: hir::HirId, - span: Span, attrs: &'a [Attribute], } impl<'a> ClosureParts<'a> { - fn new( - d: &'a FnDecl<'a>, - b: hir::BodyId, - id: hir::HirId, - s: Span, - attrs: &'a [Attribute], - ) -> Self { - ClosureParts { decl: d, body: b, id, span: s, attrs } + fn new(d: &'a FnDecl<'a>, b: hir::BodyId, id: hir::HirId, attrs: &'a [Attribute]) -> Self { + ClosureParts { decl: d, body: b, id, attrs } } } @@ -158,7 +149,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, ) } @@ -166,23 +157,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, ) } @@ -204,7 +187,7 @@ impl<'a> FnLikeNode<'a> { FnKind::ItemFn(p.ident, p.generics, p.header, p.vis, p.attrs) }; let closure = |c: ClosureParts<'a>| FnKind::Closure(c.attrs); - let method = |_, ident: Ident, sig: &'a hir::FnSig<'a>, vis, _, _, attrs| { + let method = |_, ident: Ident, sig: &'a hir::FnSig<'a>, vis, _, attrs| { FnKind::Method(ident, sig, vis, attrs) }; self.handle(item, method, closure) @@ -219,7 +202,6 @@ impl<'a> FnLikeNode<'a> { &'a hir::FnSig<'a>, Option<&'a hir::Visibility<'a>>, hir::BodyId, - Span, &'a [Attribute], ) -> A, C: FnOnce(ClosureParts<'a>) -> A, @@ -232,7 +214,6 @@ impl<'a> FnLikeNode<'a> { decl: &sig.decl, body: block, vis: &i.vis, - span: i.span, attrs: &i.attrs, header: sig.header, generics, @@ -241,19 +222,19 @@ impl<'a> FnLikeNode<'a> { }, Node::TraitItem(ti) => match ti.kind { hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => { - method(ti.hir_id, ti.ident, sig, None, body, ti.span, &ti.attrs) + method(ti.hir_id, ti.ident, sig, None, body, &ti.attrs) } _ => bug!("trait method FnLikeNode that is not fn-like"), }, Node::ImplItem(ii) => match ii.kind { hir::ImplItemKind::Fn(ref sig, body) => { - method(ii.hir_id, ii.ident, sig, Some(&ii.vis), body, ii.span, &ii.attrs) + method(ii.hir_id, ii.ident, sig, Some(&ii.vis), body, &ii.attrs) } _ => bug!("impl method FnLikeNode that is not fn-like"), }, Node::Expr(e) => match e.kind { hir::ExprKind::Closure(_, ref decl, block, _fn_decl_span, _gen) => { - closure(ClosureParts::new(&decl, block, e.hir_id, e.span, &e.attrs)) + closure(ClosureParts::new(&decl, block, e.hir_id, &e.attrs)) } _ => bug!("expr FnLikeNode that is not fn-like"), }, diff --git a/src/librustc_middle/hir/map/collector.rs b/src/librustc_middle/hir/map/collector.rs index dce06a5f7eeec..f96e42a613a98 100644 --- a/src/librustc_middle/hir/map/collector.rs +++ b/src/librustc_middle/hir/map/collector.rs @@ -118,6 +118,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { modules: _, proc_macros: _, trait_map: _, + spans: _, } = *krate; hash_body(&mut hcx, root_mod_def_path_hash, item, &mut hir_body_nodes) @@ -133,10 +134,16 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { hcx, hir_body_nodes, map: (0..definitions.def_index_count()) - .map(|_| HirOwnerData { signature: None, with_bodies: None }) + .map(|id| HirOwnerData { + spans: krate.spans.get_owner(Idx::new(id)), + signature: None, + with_bodies: None, + }) .collect(), }; + collector.insert_entry( + DUMMY_SP, hir::CRATE_HIR_ID, Entry { parent: hir::CRATE_HIR_ID, node: Node::Crate(&krate.item) }, hash, @@ -196,7 +203,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { (self.map, svh) } - fn insert_entry(&mut self, id: HirId, entry: Entry<'hir>, hash: Fingerprint) { + fn insert_entry(&mut self, span: Span, id: HirId, entry: Entry<'hir>, hash: Fingerprint) { let i = id.local_id.as_u32() as usize; let arena = self.arena; @@ -213,6 +220,12 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { let nodes = data.with_bodies.as_mut().unwrap(); + // Verify the consistency of the map from HIR lowering. + // Use DUMMY_SP when the span has been removed from the HIR. + if span != DUMMY_SP { + debug_assert!(id.local_id.index() < data.spans.len()); + debug_assert_eq!(data.spans[id.local_id], span); + } if i == 0 { // Overwrite the dummy hash with the real HIR owner hash. nodes.hash = hash; @@ -262,7 +275,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { } } - self.insert_entry(hir_id, entry, hash); + self.insert_entry(span, hir_id, entry, hash); } fn with_parent(&mut self, parent_node_id: HirId, f: F) { @@ -323,7 +336,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(DUMMY_SP, param.hir_id, node); self.with_parent(param.hir_id, |this| { intravisit::walk_param(this, param); }); @@ -336,12 +349,12 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { self.definitions.opt_hir_id_to_local_def_id(i.hir_id).unwrap() ); self.with_dep_node_owner(i.hir_id.owner, i, |this, hash| { - this.insert_with_hash(i.span, i.hir_id, Node::Item(i), hash); + this.insert_with_hash(DUMMY_SP, i.hir_id, Node::Item(i), hash); this.with_parent(i.hir_id, |this| { if let ItemKind::Struct(ref struct_def, _) = i.kind { // If this is a tuple or unit-like struct, register the constructor. if let Some(ctor_hir_id) = struct_def.ctor_hir_id() { - this.insert(i.span, ctor_hir_id, Node::Ctor(struct_def)); + this.insert(DUMMY_SP, ctor_hir_id, Node::Ctor(struct_def)); } } intravisit::walk_item(this, i); @@ -350,7 +363,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { } fn visit_foreign_item(&mut self, foreign_item: &'hir ForeignItem<'hir>) { - self.insert(foreign_item.span, foreign_item.hir_id, Node::ForeignItem(foreign_item)); + self.insert(DUMMY_SP, foreign_item.hir_id, Node::ForeignItem(foreign_item)); self.with_parent(foreign_item.hir_id, |this| { intravisit::walk_foreign_item(this, foreign_item); @@ -358,7 +371,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { } fn visit_generic_param(&mut self, param: &'hir GenericParam<'hir>) { - self.insert(param.span, param.hir_id, Node::GenericParam(param)); + self.insert(DUMMY_SP, param.hir_id, Node::GenericParam(param)); intravisit::walk_generic_param(self, param); } @@ -368,7 +381,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { self.definitions.opt_hir_id_to_local_def_id(ti.hir_id).unwrap() ); self.with_dep_node_owner(ti.hir_id.owner, ti, |this, hash| { - this.insert_with_hash(ti.span, ti.hir_id, Node::TraitItem(ti), hash); + this.insert_with_hash(DUMMY_SP, ti.hir_id, Node::TraitItem(ti), hash); this.with_parent(ti.hir_id, |this| { intravisit::walk_trait_item(this, ti); @@ -382,7 +395,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { self.definitions.opt_hir_id_to_local_def_id(ii.hir_id).unwrap() ); self.with_dep_node_owner(ii.hir_id.owner, ii, |this, hash| { - this.insert_with_hash(ii.span, ii.hir_id, Node::ImplItem(ii), hash); + this.insert_with_hash(DUMMY_SP, ii.hir_id, Node::ImplItem(ii), hash); this.with_parent(ii.hir_id, |this| { intravisit::walk_impl_item(this, ii); @@ -393,7 +406,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(DUMMY_SP, pat.hir_id, node); self.with_parent(pat.hir_id, |this| { intravisit::walk_pat(this, pat); @@ -403,7 +416,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(DUMMY_SP, arm.hir_id, node); self.with_parent(arm.hir_id, |this| { intravisit::walk_arm(this, arm); @@ -411,7 +424,11 @@ 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( + self.krate.body(constant.body).value.span, + constant.hir_id, + Node::AnonConst(constant), + ); self.with_parent(constant.hir_id, |this| { intravisit::walk_anon_const(this, constant); @@ -427,18 +444,18 @@ 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(DUMMY_SP, stmt.hir_id, Node::Stmt(stmt)); self.with_parent(stmt.hir_id, |this| { intravisit::walk_stmt(this, stmt); }); } - fn visit_path_segment(&mut self, path_span: Span, path_segment: &'hir PathSegment<'hir>) { + fn visit_path_segment(&mut self, path_segment: &'hir PathSegment<'hir>) { if let Some(hir_id) = path_segment.hir_id { - self.insert(path_span, hir_id, Node::PathSegment(path_segment)); + self.insert(path_segment.ident.span, 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>) { @@ -462,22 +479,21 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { fk: intravisit::FnKind<'hir>, fd: &'hir FnDecl<'hir>, b: BodyId, - s: Span, id: HirId, ) { assert_eq!(self.parent_node, id); - intravisit::walk_fn(self, fk, fd, b, s, id); + intravisit::walk_fn(self, fk, fd, b, id); } fn visit_block(&mut self, block: &'hir Block<'hir>) { - self.insert(block.span, block.hir_id, Node::Block(block)); + self.insert(DUMMY_SP, 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(DUMMY_SP, l.hir_id, Node::Local(l)); self.with_parent(l.hir_id, |this| intravisit::walk_local(this, l)) } @@ -499,28 +515,23 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { fn visit_macro_def(&mut self, macro_def: &'hir MacroDef<'hir>) { self.with_dep_node_owner(macro_def.hir_id.owner, macro_def, |this, hash| { - this.insert_with_hash( - macro_def.span, - macro_def.hir_id, - Node::MacroDef(macro_def), - hash, - ); + this.insert_with_hash(DUMMY_SP, 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(DUMMY_SP, 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(DUMMY_SP, 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(DUMMY_SP, field.hir_id, Node::Field(field)); self.with_parent(field.hir_id, |this| { intravisit::walk_struct_field(this, field); }); @@ -529,7 +540,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); } @@ -537,7 +548,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/src/librustc_middle/hir/map/mod.rs b/src/librustc_middle/hir/map/mod.rs index d1cfc4867a2fe..28da24722c84b 100644 --- a/src/librustc_middle/hir/map/mod.rs +++ b/src/librustc_middle/hir/map/mod.rs @@ -87,6 +87,7 @@ fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool { } pub(super) struct HirOwnerData<'hir> { + pub(super) spans: &'hir IndexVec, pub(super) signature: Option<&'hir Owner<'hir>>, pub(super) with_bodies: Option<&'hir mut OwnerNodes<'hir>>, } @@ -442,11 +443,11 @@ impl<'hir> Map<'hir> { } } - pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) { + pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, HirId) { let hir_id = self.as_local_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), } } @@ -827,41 +828,7 @@ impl<'hir> Map<'hir> { } pub fn span(&self, hir_id: HirId) -> Span { - match self.find_entry(hir_id).map(|entry| entry.node) { - Some(Node::Param(param)) => param.span, - Some(Node::Item(item)) => item.span, - Some(Node::ForeignItem(foreign_item)) => foreign_item.span, - Some(Node::TraitItem(trait_method)) => trait_method.span, - Some(Node::ImplItem(impl_item)) => impl_item.span, - Some(Node::Variant(variant)) => variant.span, - Some(Node::Field(field)) => field.span, - Some(Node::AnonConst(constant)) => self.body(constant.body).value.span, - Some(Node::Expr(expr)) => expr.span, - Some(Node::Stmt(stmt)) => stmt.span, - Some(Node::PathSegment(seg)) => seg.ident.span, - Some(Node::Ty(ty)) => ty.span, - Some(Node::TraitRef(tr)) => tr.path.span, - Some(Node::Binding(pat)) => pat.span, - Some(Node::Pat(pat)) => pat.span, - Some(Node::Arm(arm)) => arm.span, - Some(Node::Block(block)) => block.span, - Some(Node::Ctor(..)) => match self.find(self.get_parent_node(hir_id)) { - Some(Node::Item(item)) => item.span, - Some(Node::Variant(variant)) => variant.span, - _ => unreachable!(), - }, - Some(Node::Lifetime(lifetime)) => lifetime.span, - Some(Node::GenericParam(param)) => param.span, - Some(Node::Visibility(&Spanned { - node: VisibilityKind::Restricted { ref path, .. }, - .. - })) => path.span, - Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v), - Some(Node::Local(local)) => local.span, - Some(Node::MacroDef(macro_def)) => macro_def.span, - Some(Node::Crate(item)) => item.span, - None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id), - } + self.tcx.hir_owner_spans(hir_id.owner)[hir_id.local_id] } pub fn span_if_local(&self, id: DefId) -> Option { diff --git a/src/librustc_middle/hir/mod.rs b/src/librustc_middle/hir/mod.rs index 1e3676496ce39..db5c4444cf194 100644 --- a/src/librustc_middle/hir/mod.rs +++ b/src/librustc_middle/hir/mod.rs @@ -79,5 +79,6 @@ pub fn provide(providers: &mut Providers<'_>) { }; providers.hir_owner = |tcx, id| tcx.index_hir(LOCAL_CRATE).map[id].signature; providers.hir_owner_nodes = |tcx, id| tcx.index_hir(LOCAL_CRATE).map[id].with_bodies.as_deref(); + providers.hir_owner_spans = |tcx, id| &tcx.index_hir(LOCAL_CRATE).map[id].spans; map::provide(providers); } diff --git a/src/librustc_middle/middle/region.rs b/src/librustc_middle/middle/region.rs index 943a065a8b5e8..bfe4210a263a2 100644 --- a/src/librustc_middle/middle/region.rs +++ b/src/librustc_middle/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/src/librustc_middle/query/mod.rs b/src/librustc_middle/query/mod.rs index 9fd45ddf6e60e..f7017f1c76934 100644 --- a/src/librustc_middle/query/mod.rs +++ b/src/librustc_middle/query/mod.rs @@ -89,6 +89,15 @@ rustc_queries! { desc { |tcx| "HIR owner items in `{}`", tcx.def_path_str(key.to_def_id()) } } + // Gives access to the HIR spans inside the HIR owner `key`. + // + // This can be conveniently accessed by methods on `tcx.hir()`. + // Avoid calling this query directly. + query hir_owner_spans(key: LocalDefId) -> &'tcx IndexVec { + eval_always + desc { |tcx| "HIR owner spans in `{}`", tcx.def_path_str(key.to_def_id()) } + } + /// Records the type of every item. query type_of(key: DefId) -> Ty<'tcx> { desc { |tcx| "computing type of `{}`", tcx.def_path_str(key) } diff --git a/src/librustc_middle/ty/diagnostics.rs b/src/librustc_middle/ty/diagnostics.rs index a2812e117ed39..56643d5fe8d51 100644 --- a/src/librustc_middle/ty/diagnostics.rs +++ b/src/librustc_middle/ty/diagnostics.rs @@ -96,7 +96,10 @@ pub fn suggest_constraining_type_param( if def_id == tcx.lang_items().sized_trait() { // Type parameters are already `Sized` by default. - err.span_label(param.span, &format!("this type parameter needs to be `{}`", constraint)); + err.span_label( + tcx.hir().span(param.hir_id), + &format!("this type parameter needs to be `{}`", constraint), + ); return true; } let mut suggest_restrict = |span| { @@ -124,7 +127,7 @@ pub fn suggest_constraining_type_param( // | // replace with: `impl Foo + Bar` - suggest_restrict(param.span.shrink_to_hi()); + suggest_restrict(tcx.hir().span(param.hir_id).shrink_to_hi()); return true; } @@ -154,7 +157,7 @@ pub fn suggest_constraining_type_param( // fn foo(t: T) { ... } // - help: consider restricting this type parameter with `T: Foo` err.span_suggestion_verbose( - param.span.shrink_to_hi(), + tcx.hir().span(param.hir_id).shrink_to_hi(), &msg_restrict_type, format!(": {}", constraint), Applicability::MachineApplicable, diff --git a/src/librustc_middle/ty/error.rs b/src/librustc_middle/ty/error.rs index 6113359ca93a7..c4f3d7fb6dca9 100644 --- a/src/librustc_middle/ty/error.rs +++ b/src/librustc_middle/ty/error.rs @@ -821,7 +821,7 @@ fn foo(&self) -> Self::T { String::new() } { if self.type_of(self.hir().local_def_id(item.id.hir_id)) == found { db.span_label( - item.span, + self.hir().span(item.id.hir_id), "associated type defaults can't be assumed inside the \ trait defining them", ); @@ -840,7 +840,10 @@ fn foo(&self) -> Self::T { String::new() } match item.kind { hir::AssocItemKind::Type => { if self.type_of(self.hir().local_def_id(item.id.hir_id)) == found { - db.span_label(item.span, "expected this associated type"); + db.span_label( + self.hir().span(item.id.hir_id), + "expected this associated type", + ); return true; } } diff --git a/src/librustc_middle/ty/util.rs b/src/librustc_middle/ty/util.rs index 47110be53b252..a00e6333f82ea 100644 --- a/src/librustc_middle/ty/util.rs +++ b/src/librustc_middle/ty/util.rs @@ -845,7 +845,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) { @@ -1005,6 +1005,8 @@ 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 // of seen types and check recursion for each of them (issues #3008, #3779). diff --git a/src/librustc_mir/borrow_check/diagnostics/region_name.rs b/src/librustc_mir/borrow_check/diagnostics/region_name.rs index 2240eb81e1fa7..3a89f3bd80b48 100644 --- a/src/librustc_mir/borrow_check/diagnostics/region_name.rs +++ b/src/librustc_mir/borrow_check/diagnostics/region_name.rs @@ -581,7 +581,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { // doesn't happen, even in erroneous // programs. Else we should use delay-span-bug. span_bug!( - hir_arg.span(), + self.infcx.tcx.hir().span(hir_arg.id()), "unmatched subst and hir arg: found {:?} vs {:?}", kind, hir_arg, diff --git a/src/librustc_mir/transform/mod.rs b/src/librustc_mir/transform/mod.rs index 846ed1f86d8d6..c1fd3d2af518a 100644 --- a/src/librustc_mir/transform/mod.rs +++ b/src/librustc_mir/transform/mod.rs @@ -10,7 +10,7 @@ use rustc_middle::mir::{traversal, Body, ConstQualifs, MirPhase, Promoted}; use rustc_middle::ty::query::Providers; use rustc_middle::ty::steal::Steal; use rustc_middle::ty::{InstanceDef, TyCtxt, TypeFoldable}; -use rustc_span::{Span, Symbol}; +use rustc_span::Symbol; use std::borrow::Cow; pub mod add_call_guards; @@ -85,7 +85,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/src/librustc_mir_build/build/mod.rs b/src/librustc_mir_build/build/mod.rs index e2cf1bce733d6..972b208454b80 100644 --- a/src/librustc_mir_build/build/mod.rs +++ b/src/librustc_mir_build/build/mod.rs @@ -127,8 +127,9 @@ fn mir_build(tcx: TyCtxt<'_>, def_id: LocalDefId) -> 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 span = tcx.hir().span(arg.hir_id); let va_list_did = - tcx.require_lang_item(lang_items::VaListTypeLangItem, Some(arg.span)); + tcx.require_lang_item(lang_items::VaListTypeLangItem, Some(span)); tcx.type_of(va_list_did).subst(tcx, &[tcx.lifetimes.re_erased.into()]) } else { @@ -791,10 +792,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { argument_scope: region::Scope, ast_body: &'tcx hir::Expr<'tcx>, ) -> BlockAnd<()> { + let tcx = self.hir.tcx(); + let tcx_hir = tcx.hir(); + // Allocate locals for the function arguments for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() { let source_info = - SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span)); + SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| tcx.hir().span(arg.pat.hir_id))); let arg_local = self.local_decls.push(LocalDecl::with_source_info(ty, source_info)); // If this is a simple binding pattern, give debuginfo a nice name. @@ -809,8 +813,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - let tcx = self.hir.tcx(); - let tcx_hir = tcx.hir(); let hir_tables = self.hir.tables(); // In analyze_closure() in upvar.rs we gathered a list of upvars used by a @@ -843,7 +845,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { if let Some(Node::Binding(pat)) = tcx_hir.find(var_id) { if let hir::PatKind::Binding(_, _, ident, _) = pat.kind { name = ident.name; - match hir_tables.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) { + let pat_span = tcx_hir.span(pat.hir_id); + match hir_tables.extract_binding_mode(tcx.sess, pat.hir_id, pat_span) { Some(ty::BindByValue(hir::Mutability::Mut)) => { mutability = Mutability::Mut; } @@ -886,7 +889,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // Make sure we drop (parts of) the argument even when not matched on. self.schedule_drop( - arg_opt.as_ref().map_or(ast_body.span, |arg| arg.pat.span), + arg_opt.as_ref().map_or(ast_body.span, |arg| tcx_hir.span(arg.pat.hir_id)), argument_scope, local, DropKind::Value, diff --git a/src/librustc_mir_build/hair/cx/block.rs b/src/librustc_mir_build/hair/cx/block.rs index c7b53024666d9..53a50a45ce2c9 100644 --- a/src/librustc_mir_build/hair/cx/block.rs +++ b/src/librustc_mir_build/hair/cx/block.rs @@ -17,11 +17,12 @@ impl<'tcx> Mirror<'tcx> for &'tcx hir::Block<'tcx> { let stmts = mirror_stmts(cx, self.hir_id.local_id, &*self.stmts); let opt_destruction_scope = cx.region_scope_tree.opt_destruction_scope(self.hir_id.local_id); + let span = cx.tcx.hir().span(self.hir_id); Block { targeted_by_break: self.targeted_by_break, region_scope: region::Scope { id: self.hir_id.local_id, data: region::ScopeData::Node }, opt_destruction_scope, - span: self.span, + span, stmts, expr: self.expr.to_ref(), safety_mode: match self.rules { @@ -106,12 +107,8 @@ crate fn to_expr_ref<'a, 'tcx>( block: &'tcx hir::Block<'tcx>, ) -> ExprRef<'tcx> { let block_ty = cx.tables().node_type(block.hir_id); + let span = cx.tcx.hir().span(block.hir_id); let temp_lifetime = cx.region_scope_tree.temporary_scope(block.hir_id.local_id); - let expr = Expr { - ty: block_ty, - temp_lifetime, - span: block.span, - kind: ExprKind::Block { body: block }, - }; + let expr = Expr { ty: block_ty, temp_lifetime, span, kind: ExprKind::Block { body: block } }; expr.to_ref() } diff --git a/src/librustc_mir_build/hair/cx/expr.rs b/src/librustc_mir_build/hair/cx/expr.rs index a1796c9433eac..5f0262553167b 100644 --- a/src/librustc_mir_build/hair/cx/expr.rs +++ b/src/librustc_mir_build/hair/cx/expr.rs @@ -766,7 +766,7 @@ fn convert_arm<'tcx>(cx: &mut Cx<'_, 'tcx>, arm: &'tcx hir::Arm<'tcx>) -> Arm<'t body: arm.body.to_ref(), lint_level: LintLevel::Explicit(arm.hir_id), scope: region::Scope { id: arm.hir_id.local_id, data: region::ScopeData::Node }, - span: arm.span, + span: cx.tcx.hir().span(arm.hir_id), } } diff --git a/src/librustc_mir_build/hair/pattern/check_match.rs b/src/librustc_mir_build/hair/pattern/check_match.rs index 4d97a19f4086b..38ad8f09588db 100644 --- a/src/librustc_mir_build/hair/pattern/check_match.rs +++ b/src/librustc_mir_build/hair/pattern/check_match.rs @@ -64,7 +64,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), @@ -142,7 +142,8 @@ impl<'tcx> MatchVisitor<'_, 'tcx> { let pattern: &_ = cx.pattern_arena.alloc(expand_pattern(cx, 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) } @@ -206,9 +207,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, @@ -222,7 +224,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 } }; @@ -261,13 +263,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 @@ -284,8 +287,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.tables.extract_binding_mode(cx.tcx.sess, p.hir_id, p.span) + cx.tables.extract_binding_mode(cx.tcx.sess, p.hir_id, span) { let pat_ty = cx.tables.pat_ty(p).peel_refs(); if let ty::Adt(edef, _) = pat_ty.kind { @@ -297,7 +301,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!( @@ -307,7 +311,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, @@ -589,7 +593,8 @@ fn check_legality_of_move_bindings(cx: &mut MatchVisitor<'_, '_>, has_guard: boo // Find all by-ref spans. let mut by_ref_spans = Vec::new(); - pat.each_binding(|_, hir_id, span, _| { + pat.each_binding(|_, hir_id, _| { + let span = cx.tcx.hir().span(hir_id); if let Some(ty::BindByReference(_)) = tables.extract_binding_mode(sess, hir_id, span) { by_ref_spans.push(span); } @@ -602,17 +607,20 @@ fn check_legality_of_move_bindings(cx: &mut MatchVisitor<'_, '_>, has_guard: boo // // `x @ Foo(..)` is legal, but `x @ Foo(y)` isn't. if sub.map_or(false, |p| p.contains_bindings()) { - struct_span_err!(sess, p.span, E0007, "cannot bind by-move with sub-bindings") - .span_label(p.span, "binds an already bound by-move value by moving it") + let span = cx.tcx.hir().span(p.hir_id); + struct_span_err!(sess, span, E0007, "cannot bind by-move with sub-bindings") + .span_label(span, "binds an already bound by-move value by moving it") .emit(); } else if !has_guard && !by_ref_spans.is_empty() { - by_move_spans.push(p.span); + let span = cx.tcx.hir().span(p.hir_id); + by_move_spans.push(span); } }; pat.walk_always(|p| { if let hir::PatKind::Binding(.., sub) = &p.kind { - if let Some(ty::BindByValue(_)) = tables.extract_binding_mode(sess, p.hir_id, p.span) { - if is_binding_by_move(cx, p.hir_id, p.span) { + let span = cx.tcx.hir().span(p.hir_id); + if let Some(ty::BindByValue(_)) = tables.extract_binding_mode(sess, p.hir_id, span) { + if is_binding_by_move(cx, p.hir_id, span) { check_move(p, sub.as_deref()); } } @@ -653,17 +661,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 tables = cx.tables; let sess = cx.tcx.sess; // Get the binding move, extract the mutability if by-ref. - let mut_outer = match tables.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 tables.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 tables.extract_binding_mode(sess, hir_id, span) { Some(ty::BindByValue(_)) | None => {} Some(ty::BindByReference(_)) => conflicts_ref.push(span), @@ -675,7 +685,7 @@ fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_ name, tables.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") @@ -692,7 +702,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 tables.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`. @@ -710,7 +721,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)); @@ -730,7 +741,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)); @@ -742,7 +753,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)); @@ -772,10 +783,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/src/librustc_mir_build/hair/pattern/mod.rs b/src/librustc_mir_build/hair/pattern/mod.rs index 5c30b2a448c6d..54fc6ce96559b 100644 --- a/src/librustc_mir_build/hair/pattern/mod.rs +++ b/src/librustc_mir_build/hair/pattern/mod.rs @@ -365,7 +365,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 @@ -508,10 +509,11 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Pat<'tcx> { let mut ty = self.tables.node_type(pat.hir_id); + let pat_span = self.tcx.hir().span(pat.hir_id); if let ty::Error(_) = ty.kind { // Avoid ICEs (e.g., #50577 and #50585). - return Pat { span: pat.span, ty, kind: Box::new(PatKind::Wild) }; + return Pat { span: pat_span, ty, kind: Box::new(PatKind::Wild) }; } let kind = match pat.kind { @@ -521,7 +523,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { hir::PatKind::Range(ref lo_expr, ref hi_expr, end) => { let (lo_expr, hi_expr) = (lo_expr.as_deref(), hi_expr.as_deref()); - let lo_span = lo_expr.map_or(pat.span, |e| e.span); + let lo_span = lo_expr.map_or(pat_span, |e| e.span); let lo = lo_expr.map(|e| self.lower_range_expr(e)); let hi = hi_expr.map(|e| self.lower_range_expr(e)); @@ -533,7 +535,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { "found bad range pattern `{:?}` outside of error recovery", (&lo, &hi), ); - self.tcx.sess.delay_span_bug(pat.span, msg); + self.tcx.sess.delay_span_bug(pat_span, msg); PatKind::Wild } }; @@ -543,7 +545,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { // constants somewhere. Have them on the range pattern. for end in &[lo, hi] { if let Some((_, Some(ascription))) = end { - let subpattern = Pat { span: pat.span, ty, kind: Box::new(kind) }; + let subpattern = Pat { span: pat_span, ty, kind: Box::new(kind) }; kind = PatKind::AscribeUserType { ascription: *ascription, subpattern }; } } @@ -552,7 +554,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { } hir::PatKind::Path(ref qpath) => { - return self.lower_path(qpath, pat.hir_id, pat.span); + return self.lower_path(qpath, pat.hir_id, pat_span); } hir::PatKind::Ref(ref subpattern, _) | hir::PatKind::Box(ref subpattern) => { @@ -560,13 +562,13 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { } hir::PatKind::Slice(ref prefix, ref slice, ref suffix) => { - self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix) + self.slice_or_array_pattern(pat_span, ty, prefix, slice, suffix) } hir::PatKind::Tuple(ref pats, ddpos) => { let tys = match ty.kind { ty::Tuple(ref tys) => tys, - _ => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty), + _ => span_bug!(pat_span, "unexpected type for tuple pattern: {:?}", ty), }; let subpatterns = self.lower_tuple_subpats(pats, tys.len(), ddpos); PatKind::Leaf { subpatterns } @@ -612,11 +614,11 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { let res = self.tables.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, _) => { @@ -629,13 +631,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/src/librustc_passes/check_attr.rs b/src/librustc_passes/check_attr.rs index 80681c143750f..4f7d806b3c622 100644 --- a/src/librustc_passes/check_attr.rs +++ b/src/librustc_passes/check_attr.rs @@ -51,11 +51,11 @@ impl CheckAttrVisitor<'tcx> { &self, hir_id: HirId, attrs: &'hir [Attribute], - span: &Span, target: Target, item: Option<&Item<'_>>, ) { let mut is_valid = true; + let span = &self.tcx.hir().span(hir_id); for attr in attrs { is_valid &= if attr.check_name(sym::inline) { self.check_inline(hir_id, attr, span, target) @@ -357,12 +357,14 @@ impl CheckAttrVisitor<'tcx> { if let hir::StmtKind::Local(ref l) = stmt.kind { for attr in l.attrs.iter() { if attr.check_name(sym::inline) { - self.check_inline(l.hir_id, attr, &stmt.span, Target::Statement); + let span = self.tcx.hir().span(stmt.hir_id); + self.check_inline(l.hir_id, attr, &span, Target::Statement); } if attr.check_name(sym::repr) { + let span = self.tcx.hir().span(stmt.hir_id); self.emit_repr_error( attr.span, - stmt.span, + span, "attribute should not be applied to a statement", "not a struct, enum, or union", ); @@ -414,25 +416,25 @@ 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.attrs, &item.span, target, Some(item)); + self.check_attributes(item.hir_id, item.attrs, target, Some(item)); intravisit::walk_item(self, item) } 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.attrs, &trait_item.span, target, None); + self.check_attributes(trait_item.hir_id, &trait_item.attrs, target, None); intravisit::walk_trait_item(self, trait_item) } fn visit_foreign_item(&mut self, f_item: &'tcx hir::ForeignItem<'tcx>) { let target = Target::from_foreign_item(f_item); - self.check_attributes(f_item.hir_id, &f_item.attrs, &f_item.span, target, None); + self.check_attributes(f_item.hir_id, &f_item.attrs, target, None); 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.attrs, &impl_item.span, target, None); + self.check_attributes(impl_item.hir_id, &impl_item.attrs, target, None); intravisit::walk_impl_item(self, impl_item) } diff --git a/src/librustc_passes/check_const.rs b/src/librustc_passes/check_const.rs index 94f9c619a3a26..1833e60549f21 100644 --- a/src/librustc_passes/check_const.rs +++ b/src/librustc_passes/check_const.rs @@ -178,7 +178,8 @@ impl<'tcx> Visitor<'tcx> for CheckConstVisitor<'tcx> { fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { if self.const_kind.is_some() { if let hir::PatKind::Or { .. } = p.kind { - self.const_check_violated(NonConstExpr::OrPattern, p.span); + let span = self.tcx.hir().span(p.hir_id); + self.const_check_violated(NonConstExpr::OrPattern, span); } } intravisit::walk_pat(self, p) diff --git a/src/librustc_passes/dead.rs b/src/librustc_passes/dead.rs index 503fbb64db83d..dfd18382ded2f 100644 --- a/src/librustc_passes/dead.rs +++ b/src/librustc_passes/dead.rs @@ -133,7 +133,7 @@ impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> { ) { let variant = match self.tables.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 { @@ -232,7 +232,6 @@ impl<'a, 'tcx> Visitor<'tcx> for MarkSymbolVisitor<'a, '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; @@ -578,6 +577,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 span = self.tcx.hir().span(item.hir_id); let span = match item.kind { hir::ItemKind::Fn(..) | hir::ItemKind::Mod(..) @@ -592,13 +592,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 span.source_callee().is_some() { + self.tcx.sess.source_map().guess_head_span(span) } else { item.ident.span } } - _ => item.span, + _ => span, }; let participle = match item.kind { hir::ItemKind::Struct(..) => "constructed", // Issue #52325 @@ -618,7 +618,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); } @@ -626,14 +627,16 @@ 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"); + let span = self.tcx.hir().span(fi.hir_id); + self.warn_dead_code(fi.hir_id, span, fi.ident.name, "used"); } intravisit::walk_foreign_item(self, fi); } 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); } @@ -642,25 +645,22 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> { match impl_item.kind { hir::ImplItemKind::Const(_, body_id) => { if !self.symbol_is_live(impl_item.hir_id) { - self.warn_dead_code( - impl_item.hir_id, - impl_item.span, - impl_item.ident.name, - "used", - ); + let span = self.tcx.hir().span(impl_item.hir_id); + self.warn_dead_code(impl_item.hir_id, span, impl_item.ident.name, "used"); } self.visit_nested_body(body_id) } hir::ImplItemKind::Fn(_, body_id) => { if !self.symbol_is_live(impl_item.hir_id) { - // FIXME(66095): Because impl_item.span is annotated with things + // FIXME(66095): Because impl_item's span is annotated with things // like expansion data, and ident.span isn't, we use the // def_span method if it's part of a macro invocation // (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 span = self.tcx.hir().span(impl_item.hir_id); + let span = if span.source_callee().is_some() { + self.tcx.sess.source_map().guess_head_span(span) } else { impl_item.ident.span }; diff --git a/src/librustc_passes/entry.rs b/src/librustc_passes/entry.rs index e0ad0ac77476f..3b1b491872a8a 100644 --- a/src/librustc_passes/entry.rs +++ b/src/librustc_passes/entry.rs @@ -3,14 +3,14 @@ use rustc_ast::entry::EntryPointType; use rustc_errors::struct_span_err; use rustc_hir::def_id::{CrateNum, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc_hir::itemlikevisit::ItemLikeVisitor; -use rustc_hir::{HirId, ImplItem, Item, ItemKind, TraitItem}; +use rustc_hir::{HirId, ImplItem, Item, ItemKind, TraitItem, CRATE_HIR_ID}; use rustc_middle::hir::map::Map; use rustc_middle::ty::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_session::config::{CrateType, EntryFnType}; use rustc_session::Session; use rustc_span::symbol::sym; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::DUMMY_SP; struct EntryContext<'a, 'tcx> { session: &'a Session, @@ -18,17 +18,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> { @@ -104,37 +104,41 @@ fn find_item(item: &Item<'_>, ctxt: &mut EntryContext<'_, '_>, at_root: bool) { match entry_point_type(item, at_root) { 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") - .emit(); + let span = ctxt.map.span(item.hir_id); + struct_span_err!(ctxt.session, 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 span = ctxt.map.span(item.hir_id); + let other_span = ctxt.map.span(ctxt.attr_main_fn.unwrap()); struct_span_err!( ctxt.session, - item.span, + 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(span, "additional `#[main]` function") + .span_label(other_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 span = ctxt.map.span(item.hir_id); + let other_span = ctxt.map.span(ctxt.start_fn.unwrap()); + struct_span_err!(ctxt.session, span, E0138, "multiple `start` functions") + .span_label(other_span, "previous `#[start]` function here") + .span_label(span, "multiple `start` functions") .emit(); } } @@ -146,11 +150,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); @@ -159,7 +163,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. @@ -177,7 +181,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(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"); diff --git a/src/librustc_passes/hir_stats.rs b/src/librustc_passes/hir_stats.rs index 139ffb9699ad2..b994c2ffffbf7 100644 --- a/src/librustc_passes/hir_stats.rs +++ b/src/librustc_passes/hir_stats.rs @@ -124,7 +124,7 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { hir_visit::walk_item(self, i) } - fn visit_mod(&mut self, m: &'v hir::Mod<'v>, _s: Span, n: hir::HirId) { + fn visit_mod(&mut self, m: &'v hir::Mod<'v>, n: hir::HirId) { self.record("Mod", Id::None, m); hir_visit::walk_mod(self, m, n) } @@ -174,11 +174,10 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { fk: hir_visit::FnKind<'v>, fd: &'v hir::FnDecl<'v>, b: hir::BodyId, - s: Span, id: hir::HirId, ) { self.record("FnDecl", Id::None, fd); - hir_visit::walk_fn(self, fk, fd, b, s, id) + hir_visit::walk_fn(self, fk, fd, b, id) } fn visit_where_predicate(&mut self, predicate: &'v hir::WherePredicate<'v>) { @@ -221,9 +220,9 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { hir_visit::walk_lifetime(self, lifetime) } - fn visit_qpath(&mut self, qpath: &'v hir::QPath<'v>, id: hir::HirId, span: Span) { + fn visit_qpath(&mut self, qpath: &'v hir::QPath<'v>, id: hir::HirId) { self.record("QPath", Id::None, qpath); - hir_visit::walk_qpath(self, qpath, id, span) + hir_visit::walk_qpath(self, qpath, id) } fn visit_path(&mut self, path: &'v hir::Path<'v>, _id: hir::HirId) { @@ -231,9 +230,9 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { hir_visit::walk_path(self, path) } - fn visit_path_segment(&mut self, path_span: Span, path_segment: &'v hir::PathSegment<'v>) { + fn visit_path_segment(&mut self, path_segment: &'v hir::PathSegment<'v>) { self.record("PathSegment", Id::None, path_segment); - hir_visit::walk_path_segment(self, path_span, path_segment) + hir_visit::walk_path_segment(self, path_segment) } fn visit_assoc_type_binding(&mut self, type_binding: &'v hir::TypeBinding<'v>) { diff --git a/src/librustc_passes/layout_test.rs b/src/librustc_passes/layout_test.rs index 2419e6965968e..d042c9c03fed3 100644 --- a/src/librustc_passes/layout_test.rs +++ b/src/librustc_passes/layout_test.rs @@ -47,6 +47,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 span = self.tcx.hir().span(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. @@ -55,24 +56,20 @@ 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(span, &format!("abi: {:?}", ty_layout.abi)); } sym::align => { - self.tcx - .sess - .span_err(item.span, &format!("align: {:?}", ty_layout.align)); + self.tcx.sess.span_err(span, &format!("align: {:?}", ty_layout.align)); } sym::size => { - self.tcx - .sess - .span_err(item.span, &format!("size: {:?}", ty_layout.size)); + self.tcx.sess.span_err(span, &format!("size: {:?}", ty_layout.size)); } sym::homogeneous_aggregate => { self.tcx.sess.span_err( - item.span, + span, &format!( "homogeneous_aggregate: {:?}", ty_layout @@ -85,7 +82,7 @@ impl LayoutTest<'tcx> { let normalized_ty = self.tcx.normalize_erasing_regions(param_env.with_reveal_all(), ty); self.tcx.sess.span_err( - item.span, + span, &format!("layout_of({:?}) = {:#?}", normalized_ty, *ty_layout), ); } @@ -101,7 +98,7 @@ impl LayoutTest<'tcx> { } Err(layout_error) => { - self.tcx.sess.span_err(item.span, &format!("layout error: {:?}", layout_error)); + self.tcx.sess.span_err(span, &format!("layout error: {:?}", layout_error)); } } } diff --git a/src/librustc_passes/liveness.rs b/src/librustc_passes/liveness.rs index ff5dabd5418c9..b2a371bb319e0 100644 --- a/src/librustc_passes/liveness.rs +++ b/src/librustc_passes/liveness.rs @@ -155,10 +155,9 @@ impl<'tcx> Visitor<'tcx> for IrMaps<'tcx> { fk: FnKind<'tcx>, fd: &'tcx hir::FnDecl<'tcx>, b: hir::BodyId, - s: Span, id: HirId, ) { - visit_fn(self, fk, fd, b, s, id); + visit_fn(self, fk, fd, b, id); } fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { @@ -342,7 +341,6 @@ fn visit_fn<'tcx>( fk: FnKind<'tcx>, decl: &'tcx hir::FnDecl<'tcx>, body_id: hir::BodyId, - sp: Span, id: hir::HirId, ) { debug!("visit_fn {:?}", id); @@ -378,7 +376,7 @@ fn visit_fn<'tcx>( rustc_hir::PatKind::Struct(..) => true, _ => false, }; - param.pat.each_binding(|_bm, hir_id, _x, ident| { + param.pat.each_binding(|_bm, hir_id, ident| { debug!("adding parameters {:?}", hir_id); let var = if is_shorthand { Local(LocalInfo { id: hir_id, name: ident.name, is_shorthand: true }) @@ -391,11 +389,11 @@ fn visit_fn<'tcx>( // gather up the various local variables, significant expressions, // and so forth: - intravisit::walk_fn(&mut fn_maps, fk, decl, body_id, sp, id); + intravisit::walk_fn(&mut fn_maps, fk, decl, body_id, id); // compute liveness let mut lsets = Liveness::new(&mut fn_maps, def_id); - let entry_ln = lsets.compute(fk, &body, sp, id); + let entry_ln = lsets.compute(fk, &body, id); lsets.log_liveness(entry_ln, id); // check for various error conditions @@ -435,7 +433,7 @@ fn add_from_pat(ir: &mut IrMaps<'_>, pat: &hir::Pat<'_>) { } } - pat.each_binding(|_, hir_id, _, ident| { + pat.each_binding(|_, hir_id, ident| { ir.add_live_node_for_node(hir_id, VarDefNode(ident.span)); ir.add_variable(Local(LocalInfo { id: hir_id, @@ -709,7 +707,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); @@ -907,13 +906,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { self.rwu_table.assign_unpacked(idx, rwu); } - fn compute( - &mut self, - fk: FnKind<'_>, - body: &hir::Body<'_>, - span: Span, - id: hir::HirId, - ) -> LiveNode { + fn compute(&mut self, fk: FnKind<'_>, body: &hir::Body<'_>, id: hir::HirId) -> LiveNode { debug!("compute: using id for body, {:?}", body.value); // # Liveness of captured variables @@ -965,6 +958,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { }, ty::Generator(..) => return succ, _ => { + let span = self.ir.tcx.hir().span(id); span_bug!(span, "type of closure expr {:?} is not a closure {:?}", id, ty,); } }; @@ -974,7 +968,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { loop { self.init_from_succ(self.s.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.s.closure_ln, var); }) @@ -1676,7 +1670,8 @@ impl<'tcx> Liveness<'_, 'tcx> { // patterns so the suggestions to prefix with underscores will apply to those too. let mut vars: FxIndexMap)> = <_>::default(); - pat.each_binding(|_, hir_id, pat_sp, ident| { + pat.each_binding(|_, hir_id, ident| { + let pat_sp = self.ir.tcx.hir().span(hir_id); let ln = entry_ln.unwrap_or_else(|| self.live_node(hir_id, pat_sp)); let var = self.variable(hir_id, ident.span); let id_and_sp = (hir_id, pat_sp); diff --git a/src/librustc_passes/loops.rs b/src/librustc_passes/loops.rs index 767a6909d31d4..0dbf09d4d5a2f 100644 --- a/src/librustc_passes/loops.rs +++ b/src/librustc_passes/loops.rs @@ -144,6 +144,7 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { match destination.target_id { Ok(loop_id) => { if let Node::Block(block) = self.hir_map.find(loop_id).unwrap() { + let block_span = self.hir_map.span(block.hir_id); struct_span_err!( self.sess, e.span, @@ -151,7 +152,7 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { "`continue` pointing to a labeled block" ) .span_label(e.span, "labeled blocks cannot be `continue`'d") - .span_label(block.span, "labeled block the `continue` points to") + .span_label(block_span, "labeled block the `continue` points to") .emit(); } } diff --git a/src/librustc_passes/reachable.rs b/src/librustc_passes/reachable.rs index c9a4428c007aa..8d714e7655ad7 100644 --- a/src/librustc_passes/reachable.rs +++ b/src/librustc_passes/reachable.rs @@ -55,7 +55,7 @@ fn method_might_be_inlined( } match tcx.hir().find(tcx.hir().as_local_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 => span_bug!(tcx.hir().span(impl_item.hir_id), "impl did is not an item"), } } diff --git a/src/librustc_passes/region.rs b/src/librustc_passes/region.rs index a6fa677cbc0af..01323a3992b5c 100644 --- a/src/librustc_passes/region.rs +++ b/src/librustc_passes/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/src/librustc_passes/stability.rs b/src/librustc_passes/stability.rs index 054748c09fc44..dddacc8d23d6c 100644 --- a/src/librustc_passes/stability.rs +++ b/src/librustc_passes/stability.rs @@ -53,18 +53,18 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { &mut self, hir_id: HirId, attrs: &[Attribute], - item_sp: Span, kind: AnnotationKind, visit_children: F, ) where F: FnOnce(&mut Self), { if !self.tcx.features().staged_api { - self.forbid_staged_api_attrs(hir_id, attrs, item_sp, kind, visit_children); + self.forbid_staged_api_attrs(hir_id, attrs, kind, visit_children); return; } // This crate explicitly wants staged API. + let item_sp = self.tcx.hir().span(hir_id); debug!("annotate(id = {:?}, attrs = {:?})", hir_id, attrs); if let Some(..) = attr::find_deprecation(&self.tcx.sess.parse_sess, attrs, item_sp) { @@ -198,7 +198,6 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { &mut self, hir_id: HirId, attrs: &[Attribute], - item_sp: Span, kind: AnnotationKind, visit_children: impl FnOnce(&mut Self), ) { @@ -232,6 +231,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { } } + let item_sp = self.tcx.hir().span(hir_id); if let Some(depr) = attr::find_deprecation(&self.tcx.sess.parse_sess, attrs, item_sp) { if kind == AnnotationKind::Prohibited { self.tcx.sess.span_err(item_sp, "This deprecation annotation is useless"); @@ -280,18 +280,18 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { } hir::ItemKind::Struct(ref sd, _) => { if let Some(ctor_hir_id) = sd.ctor_hir_id() { - self.annotate(ctor_hir_id, &i.attrs, i.span, AnnotationKind::Required, |_| {}) + self.annotate(ctor_hir_id, &i.attrs, AnnotationKind::Required, |_| {}) } } _ => {} } - self.annotate(i.hir_id, &i.attrs, i.span, kind, |v| intravisit::walk_item(v, i)); + self.annotate(i.hir_id, &i.attrs, kind, |v| intravisit::walk_item(v, i)); self.in_trait_impl = orig_in_trait_impl; } fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) { - self.annotate(ti.hir_id, &ti.attrs, ti.span, AnnotationKind::Required, |v| { + self.annotate(ti.hir_id, &ti.attrs, AnnotationKind::Required, |v| { intravisit::walk_trait_item(v, ti); }); } @@ -299,15 +299,15 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) { let kind = if self.in_trait_impl { AnnotationKind::Prohibited } else { AnnotationKind::Required }; - self.annotate(ii.hir_id, &ii.attrs, ii.span, kind, |v| { + self.annotate(ii.hir_id, &ii.attrs, kind, |v| { intravisit::walk_impl_item(v, ii); }); } fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) { - self.annotate(var.id, &var.attrs, var.span, AnnotationKind::Required, |v| { + self.annotate(var.id, &var.attrs, AnnotationKind::Required, |v| { if let Some(ctor_hir_id) = var.data.ctor_hir_id() { - v.annotate(ctor_hir_id, &var.attrs, var.span, AnnotationKind::Required, |_| {}); + v.annotate(ctor_hir_id, &var.attrs, AnnotationKind::Required, |_| {}); } intravisit::walk_variant(v, var, g, item_id) @@ -315,19 +315,19 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { } fn visit_struct_field(&mut self, s: &'tcx StructField<'tcx>) { - self.annotate(s.hir_id, &s.attrs, s.span, AnnotationKind::Required, |v| { + self.annotate(s.hir_id, &s.attrs, AnnotationKind::Required, |v| { intravisit::walk_struct_field(v, s); }); } fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) { - self.annotate(i.hir_id, &i.attrs, i.span, AnnotationKind::Required, |v| { + self.annotate(i.hir_id, &i.attrs, AnnotationKind::Required, |v| { intravisit::walk_foreign_item(v, i); }); } fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef<'tcx>) { - self.annotate(md.hir_id, &md.attrs, md.span, AnnotationKind::Required, |_| {}); + self.annotate(md.hir_id, &md.attrs, AnnotationKind::Required, |_| {}); } } @@ -337,13 +337,14 @@ struct MissingStabilityAnnotations<'a, 'tcx> { } impl<'a, 'tcx> MissingStabilityAnnotations<'a, '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(hir_id); self.tcx.sess.span_err(span, &format!("{} has missing stability attribute", descr)); } } @@ -364,42 +365,42 @@ impl<'a, 'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'a, 'tcx> { // optional. They inherit stability from their parents when unannotated. hir::ItemKind::Impl { of_trait: None, .. } | hir::ItemKind::ForeignMod(..) => {} - _ => self.check_missing_stability(i.hir_id, i.span), + _ => self.check_missing_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) { - self.check_missing_stability(var.id, var.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>) { - self.check_missing_stability(s.hir_id, s.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>) { - self.check_missing_stability(md.hir_id, md.span); + self.check_missing_stability(md.hir_id); } } @@ -459,13 +460,9 @@ fn new_index(tcx: TyCtxt<'tcx>) -> Index<'tcx> { annotator.parent_stab = Some(stability); } - annotator.annotate( - hir::CRATE_HIR_ID, - &krate.item.attrs, - krate.item.span, - AnnotationKind::Required, - |v| intravisit::walk_crate(v, krate), - ); + annotator.annotate(hir::CRATE_HIR_ID, &krate.item.attrs, AnnotationKind::Required, |v| { + intravisit::walk_crate(v, krate) + }); } index } @@ -499,10 +496,11 @@ impl Visitor<'tcx> for Checker<'tcx> { } fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { + let item_span = self.tcx.hir().span(item.hir_id); match item.kind { hir::ItemKind::ExternCrate(_) => { // compiler-generated `extern crate` items have a dummy span. - if item.span.is_dummy() { + if item_span.is_dummy() { return; } @@ -512,7 +510,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 @@ -522,6 +520,7 @@ impl Visitor<'tcx> for Checker<'tcx> { if let Res::Def(DefKind::Trait, trait_did) = t.path.res { for impl_item_ref in items { let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); + let impl_item_span = self.tcx.hir().span(impl_item.hir_id); let trait_item_def_id = self .tcx .associated_items(trait_did) @@ -530,7 +529,7 @@ 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); + self.tcx.check_stability(def_id, None, impl_item_span); } } } @@ -547,7 +546,7 @@ impl Visitor<'tcx> for Checker<'tcx> { feature_err( &self.tcx.sess.parse_sess, sym::untagged_unions, - item.span, + item_span, "unions with `Drop` implementations are unstable", ) .emit(); @@ -557,7 +556,7 @@ impl Visitor<'tcx> for Checker<'tcx> { feature_err( &self.tcx.sess.parse_sess, sym::untagged_unions, - item.span, + item_span, "unions with non-`Copy` fields are unstable", ) .emit(); @@ -587,7 +586,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); intravisit::walk_crate(&mut missing, krate); krate.visit_all_item_likes(&mut missing.as_deep_visitor()); } diff --git a/src/librustc_passes/weak_lang_items.rs b/src/librustc_passes/weak_lang_items.rs index f2f07b5d4fb26..e5b6bb4fa80da 100644 --- a/src/librustc_passes/weak_lang_items.rs +++ b/src/librustc_passes/weak_lang_items.rs @@ -12,7 +12,6 @@ use rustc_middle::ty::TyCtxt; use rustc_session::config::CrateType; use rustc_span::symbol::sym; use rustc_span::symbol::Symbol; -use rustc_span::Span; struct Context<'a, 'tcx> { tcx: TyCtxt<'tcx>, @@ -72,7 +71,7 @@ fn verify<'tcx>(tcx: TyCtxt<'tcx>, items: &lang_items::LanguageItems) { } impl<'a, 'tcx> Context<'a, 'tcx> { - fn register(&mut self, name: Symbol, span: Span, hir_id: hir::HirId) { + fn register(&mut self, name: Symbol, hir_id: hir::HirId) { if let Some(&item) = WEAK_ITEMS_REFS.get(&name) { if self.items.require(item).is_err() { self.items.missing.push(item); @@ -88,6 +87,7 @@ impl<'a, 'tcx> Context<'a, 'tcx> { } } } else { + let span = self.tcx.hir().span(hir_id); struct_span_err!(self.tcx.sess, span, E0264, "unknown external lang item: `{}`", name) .emit(); } @@ -103,7 +103,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { fn visit_foreign_item(&mut self, i: &hir::ForeignItem<'_>) { if let Some((lang_item, _)) = hir::lang_items::extract(&i.attrs) { - self.register(lang_item, i.span, i.hir_id); + self.register(lang_item, i.hir_id); } intravisit::walk_foreign_item(self, i) } diff --git a/src/librustc_plugin_impl/build.rs b/src/librustc_plugin_impl/build.rs index 34522cfe97f35..fef6cad3d08c5 100644 --- a/src/librustc_plugin_impl/build.rs +++ b/src/librustc_plugin_impl/build.rs @@ -7,17 +7,16 @@ 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 { - registrars: Vec<(hir::HirId, Span)>, + registrars: Vec, } impl<'v> ItemLikeVisitor<'v> for RegistrarFinder { fn visit_item(&mut self, item: &hir::Item<'_>) { if let hir::ItemKind::Fn(..) = item.kind { if attr::contains_name(&item.attrs, sym::plugin_registrar) { - self.registrars.push((item.hir_id, item.span)); + self.registrars.push(item.hir_id); } } } @@ -41,13 +40,14 @@ fn plugin_registrar_fn(tcx: TyCtxt<'_>, cnum: CrateNum) -> Option { match finder.registrars.len() { 0 => None, 1 => { - let (hir_id, _) = finder.registrars.pop().unwrap(); + let hir_id = finder.registrars.pop().unwrap(); Some(tcx.hir().local_def_id(hir_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 &hir_id in &finder.registrars { + let span = tcx.hir().span(hir_id); e.span_note(span, "one is here"); } e.emit(); diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 9e6e7ea962bc3..8772c37aec0a6 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -242,7 +242,8 @@ fn def_id_visibility<'tcx>( Node::ForeignItem(foreign_item) => &foreign_item.vis, Node::MacroDef(macro_def) => { if attr::contains_name(¯o_def.attrs, sym::macro_export) { - return (ty::Visibility::Public, macro_def.span, "public"); + let span = tcx.hir().span(macro_def.hir_id); + return (ty::Visibility::Public, span, "public"); } else { ¯o_def.vis } @@ -911,7 +912,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() { @@ -1081,7 +1082,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, '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` } @@ -1130,16 +1131,17 @@ impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> { .iter() .find(|f| self.tcx.field_index(f.hir_id, self.tables) == 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.tables); - self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); + self.check_field(use_ctxt, field_span, adt, &variant.fields[index], false); } } } @@ -1155,7 +1157,8 @@ impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> { for field in fields { let use_ctxt = field.ident.span; let index = self.tcx.field_index(field.hir_id, self.tables); - 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); } } @@ -1223,7 +1226,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, '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` } @@ -1326,7 +1329,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, '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 self.tables.qpath_res(qpath, id) { Res::Def(kind, def_id) => Some((kind, def_id)), _ => None, @@ -1350,6 +1353,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, '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(); @@ -1357,12 +1361,13 @@ impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> { } } - intravisit::walk_qpath(self, qpath, id, span); + intravisit::walk_qpath(self, qpath, id); } // Check types of patterns. fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) { - if self.check_expr_pat_type(pattern.hir_id, pattern.span) { + let span = self.tcx.hir().span(pattern.hir_id); + if self.check_expr_pat_type(pattern.hir_id, span) { // Do not check nested patterns if the error already happened. return; } @@ -2075,7 +2080,8 @@ fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { current_item: None, empty_tables: &empty_tables, }; - 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/src/librustc_resolve/late/diagnostics.rs b/src/librustc_resolve/late/diagnostics.rs index 478698ba20c70..9f22e9aa3a0ae 100644 --- a/src/librustc_resolve/late/diagnostics.rs +++ b/src/librustc_resolve/late/diagnostics.rs @@ -1029,7 +1029,8 @@ impl<'tcx> LifetimeContext<'_, 'tcx> { } => false, _ => true, }) { - (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 { (generics.span, format!("<{}>", lifetime_ref)) }; @@ -1072,7 +1073,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 }); @@ -1125,7 +1129,8 @@ impl<'tcx> LifetimeContext<'_, 'tcx> { } => false, _ => true, }) { - (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/src/librustc_resolve/late/lifetimes.rs b/src/librustc_resolve/late/lifetimes.rs index 903eee672cf1f..a2a67b1febf94 100644 --- a/src/librustc_resolve/late/lifetimes.rs +++ b/src/librustc_resolve/late/lifetimes.rs @@ -481,7 +481,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 { @@ -1004,8 +1006,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 { @@ -1021,7 +1024,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(); @@ -1194,7 +1197,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(item.hir_id); + tcx.sess.span_err(item_span, &object_lifetime_default_reprs); } map.insert(item.hir_id, result); @@ -1342,8 +1346,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { in_band = true; } } + let param_span = self.tcx.hir().span(param.hir_id); if in_band { - Some(param.span) + Some(param_span) } else { if generics.params.len() == 1 { // if sole lifetime, remove the entire `<>` brackets @@ -1352,9 +1357,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 other_span = self.tcx.hir().span(generics.params[i - 1].hir_id); + Some(other_span.shrink_to_hi().to(param_span)) } else { - Some(param.span.to(generics.params[i + 1].span.shrink_to_lo())) + let other_span = self.tcx.hir().span(generics.params[i + 1].hir_id); + Some(param_span.to(other_span.shrink_to_lo())) } } } @@ -1513,7 +1520,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, } { @@ -1574,7 +1582,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, } { @@ -2494,17 +2503,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(); } } @@ -2512,15 +2519,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(); } } @@ -2537,10 +2546,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(), @@ -2584,7 +2594,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { self.tcx, label.name, original_label(label.span), - shadower_lifetime(¶m), + shadower_lifetime(self.tcx, ¶m), ); return; } @@ -2611,7 +2621,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; } @@ -2811,7 +2821,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/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index e63e31e03c9f0..ffdb7fb00ea85 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -128,7 +128,7 @@ impl<'l, 'tcx> DumpVisitor<'l, '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<'l, 'tcx> DumpVisitor<'l, '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); @@ -366,7 +366,7 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { self.nest_tables(map.local_def_id(item.hir_id), |v| { let body = map.body(body); if let Some(fn_data) = v.save_ctxt.get_item_data(item) { - down_cast_data!(fn_data, DefData, item.span); + down_cast_data!(fn_data, DefData, v.tcx.hir().span(item.hir_id)); v.process_formals(body.params, &fn_data.qualname); v.process_generic_params(ty_params, &fn_data.qualname, item.hir_id); @@ -393,7 +393,7 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { ) { self.nest_tables(self.tcx.hir().local_def_id(item.hir_id), |v| { if let Some(var_data) = v.save_ctxt.get_item_data(item) { - down_cast_data!(var_data, DefData, item.span); + down_cast_data!(var_data, DefData, v.tcx.hir().span(item.hir_id)); v.dumper.dump_def(&access_from!(v.save_ctxt, item, item.hir_id), var_data); } v.visit_ty(&typ); @@ -453,7 +453,7 @@ impl<'l, 'tcx> DumpVisitor<'l, '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!( "::{}", @@ -529,7 +529,7 @@ impl<'l, 'tcx> DumpVisitor<'l, '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); @@ -630,12 +630,13 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { impl_items: &'tcx [hir::ImplItemRef<'tcx>], ) { if let Some(impl_data) = self.save_ctxt.get_item_data(item) { - if !self.span.filter_generated(item.span) { + let item_span = self.tcx.hir().span(item.hir_id); + if !self.span.filter_generated(item_span) { if let super::Data::RelationData(rel, imp) = impl_data { self.dumper.dump_relation(rel); self.dumper.dump_impl(imp); } else { - span_bug!(item.span, "unexpected data kind: {:?}", impl_data); + span_bug!(item_span, "unexpected data kind: {:?}", impl_data); } } } @@ -742,7 +743,7 @@ impl<'l, 'tcx> DumpVisitor<'l, '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); } } @@ -811,8 +812,8 @@ impl<'l, 'tcx> DumpVisitor<'l, '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); } @@ -834,10 +835,11 @@ impl<'l, 'tcx> DumpVisitor<'l, '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); } } @@ -961,7 +963,9 @@ impl<'l, 'tcx> DumpVisitor<'l, '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(); @@ -998,8 +1002,8 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { } fn process_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>, trait_id: DefId) { - self.process_macro_use(trait_item.span); - let vis_span = trait_item.span.shrink_to_lo(); + self.process_macro_use(trait_item.hir_id); + let vis_span = self.tcx.hir().span(trait_item.hir_id).shrink_to_lo(); match trait_item.kind { hir::TraitItemKind::Const(ref ty, body) => { let body = body.map(|b| &self.tcx.hir().body(b).value); @@ -1025,7 +1029,7 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { trait_item.ident, &trait_item.generics, &respan, - trait_item.span, + self.tcx.hir().span(trait_item.hir_id), ); } hir::TraitItemKind::Type(ref bounds, ref default_ty) => { @@ -1049,7 +1053,7 @@ impl<'l, 'tcx> DumpVisitor<'l, '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, @@ -1077,7 +1081,7 @@ impl<'l, 'tcx> DumpVisitor<'l, '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); @@ -1099,7 +1103,7 @@ impl<'l, 'tcx> DumpVisitor<'l, '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) => { @@ -1117,7 +1121,9 @@ impl<'l, 'tcx> DumpVisitor<'l, '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 @@ -1126,7 +1132,6 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { .iter() .map(|i| id_from_hir_id(i.id, &self.save_ctxt)) .collect(); - let span = self.span_from_span(krate.item.span); self.dumper.dump_def( &Access { public: true, reachable: true }, @@ -1168,7 +1173,7 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, '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; @@ -1206,10 +1211,11 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, '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` + let item_span = self.tcx.hir().span(item.hir_id); if let Some(sub_span) = - self.span.sub_span_of_token(item.span, token::BinOp(token::Star)) + self.span.sub_span_of_token(item_span, token::BinOp(token::Star)) { - if !self.span.filter_generated(item.span) { + if !self.span.filter_generated(item_span) { let access = access_from!(self.save_ctxt, item, item.hir_id); let span = self.span_from_span(sub_span); let parent = self @@ -1347,10 +1353,10 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, '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; } @@ -1370,7 +1376,7 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, '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); @@ -1389,7 +1395,7 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, '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 base) => { let hir_expr = self.save_ctxt.tcx.hir().expect_expr(ex.hir_id); @@ -1410,8 +1416,9 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, '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); } } @@ -1450,7 +1457,7 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, '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); } @@ -1462,17 +1469,17 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, 'tcx> { self.visit_expr(&arm.body); } - fn visit_qpath(&mut self, path: &'tcx hir::QPath<'tcx>, id: hir::HirId, _: Span) { + fn visit_qpath(&mut self, path: &'tcx hir::QPath<'tcx>, id: hir::HirId) { self.process_path(id, path); } fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) { - self.process_macro_use(s.span); + self.process_macro_use(s.hir_id); intravisit::walk_stmt(self, s) } fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { - self.process_macro_use(l.span); + self.process_macro_use(l.hir_id); self.process_var_decl(&l.pat); // Just walk the initialiser and type (don't want to walk the pattern again). @@ -1486,7 +1493,7 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, '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); @@ -1502,7 +1509,7 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, '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); } @@ -1510,7 +1517,7 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, '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/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index f5c3e84c62426..4c586331cd66b 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -296,8 +296,13 @@ impl<'l, 'tcx> SaveContext<'l, '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), @@ -885,7 +890,9 @@ impl<'l> Visitor<'l> for PathCollector<'l> { hir::PatKind::Binding(bm, _, ident, _) => { debug!( "PathCollector, visit ident in pat {}: {:?} {:?}", - ident, p.span, ident.span + ident, + self.tcx.hir().span(p.hir_id), + ident.span ); let immut = match bm { // Even if the ref is mut, you can't change the ref, only diff --git a/src/librustc_trait_selection/traits/error_reporting/mod.rs b/src/librustc_trait_selection/traits/error_reporting/mod.rs index fd0c1a54d27ad..e1c17074b0633 100644 --- a/src/librustc_trait_selection/traits/error_reporting/mod.rs +++ b/src/librustc_trait_selection/traits/error_reporting/mod.rs @@ -777,38 +777,37 @@ 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())) } }) .collect::>>()?, ), - Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. }) + Node::Item(&hir::Item { hir_id, kind: hir::ItemKind::Fn(ref sig, ..), .. }) | Node::ImplItem(&hir::ImplItem { - span, + hir_id, kind: hir::ImplItemKind::Fn(ref sig, _), .. }) | Node::TraitItem(&hir::TraitItem { - span, + hir_id, kind: hir::TraitItemKind::Fn(ref sig, _), .. }) => ( - sm.guess_head_span(span), + sm.guess_head_span(hir.span(hir_id)), sig.decl .inputs .iter() @@ -1718,7 +1717,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() @@ -1748,9 +1748,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/src/librustc_trait_selection/traits/error_reporting/suggestions.rs b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs index 176bd90303ddd..c02ddabf164ac 100644 --- a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs +++ b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs @@ -274,7 +274,7 @@ fn suggest_restriction( // `fn foo(t: impl Trait)` // ^^^ suggest `` here Some(param) => ( - param.bounds_span().unwrap_or(param.span).shrink_to_hi(), + param.bounds_span().unwrap_or(tcx.hir().span(param.hir_id)).shrink_to_hi(), format!(", {}", type_param), ), }, @@ -922,7 +922,8 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { // no return, suggest removal of semicolon on last statement. // Once that is added, close #54771. if let Some(ref stmt) = blk.stmts.last() { - let sp = self.tcx.sess.source_map().end_point(stmt.span); + let span = self.tcx.hir().span(stmt.hir_id); + let sp = self.tcx.sess.source_map().end_point(span); err.span_label(sp, "consider removing this semicolon"); } } diff --git a/src/librustc_trait_selection/traits/wf.rs b/src/librustc_trait_selection/traits/wf.rs index 1825c159ff3fb..2bf0203be16a6 100644 --- a/src/librustc_trait_selection/traits/wf.rs +++ b/src/librustc_trait_selection/traits/wf.rs @@ -190,7 +190,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), }; match pred.kind() { ty::PredicateKind::Projection(proj) => { diff --git a/src/librustc_ty/ty.rs b/src/librustc_ty/ty.rs index 595992d01dd2d..54439e6090c18 100644 --- a/src/librustc_ty/ty.rs +++ b/src/librustc_ty/ty.rs @@ -156,8 +156,9 @@ fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem { _ => {} } + let parent_item_span = tcx.hir().span(parent_id); span_bug!( - parent_item.span, + parent_item_span, "unexpected parent of trait or impl item or item not found: {:?}", parent_item.kind ) @@ -214,7 +215,7 @@ fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] { .map(|id| tcx.hir().local_def_id(id.hir_id).to_def_id()), ), hir::ItemKind::TraitAlias(..) => &[], - _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"), + _ => span_bug!(tcx.hir().span(id), "associated_item_def_ids: not impl or trait"), } } diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 33d57e2571173..01bec1b8cdfe6 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -26,7 +26,6 @@ use rustc_middle::ty::{ use rustc_middle::ty::{GenericParamDef, GenericParamDefKind}; use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, LATE_BOUND_LIFETIME_ARGUMENTS}; use rustc_session::parse::feature_err; -use rustc_session::Session; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::{MultiSpan, Span, DUMMY_SP}; use rustc_target::spec::abi; @@ -260,12 +259,13 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { }); if explicit && impl_trait { + let hir = tcx.hir(); let spans = seg .generic_args() .args .iter() .filter_map(|arg| match arg { - GenericArg::Type(_) => Some(arg.span()), + GenericArg::Type(_) => Some(hir.span(arg.id())), _ => None, }) .collect::>(); @@ -342,7 +342,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } if position != GenericArgPosition::Type && !args.bindings.is_empty() { - AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span); + AstConv::prohibit_assoc_ty_binding(tcx, tcx.hir().span(args.bindings[0].hir_id)); } let explicit_late_bound = @@ -388,7 +388,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // we want to point to the unexpected arguments. let spans: Vec = args.args[offset + permitted..offset + provided] .iter() - .map(|arg| arg.span()) + .map(|arg| tcx.hir().span(arg.id())) .collect(); unexpected_spans.extend(spans.clone()); (spans, format!("unexpected {} argument", kind)) @@ -475,10 +475,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// Report an error that a generic argument did not match the generic parameter that was /// expected. - fn generic_arg_mismatch_err(sess: &Session, arg: &GenericArg<'_>, kind: &'static str) { + fn generic_arg_mismatch_err(tcx: TyCtxt<'_>, arg: &GenericArg<'_>, kind: &'static str) { let mut err = struct_span_err!( - sess, - arg.span(), + tcx.sess, + tcx.hir().span(arg.id()), E0747, "{} provided when a {} was expected", arg.descr(), @@ -648,7 +648,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { if arg_count.correct.is_ok() && arg_count.explicit_late_bound == ExplicitLateBound::No { - Self::generic_arg_mismatch_err(tcx.sess, arg, kind.descr()); + Self::generic_arg_mismatch_err(tcx, arg, kind.descr()); } // We've reported the error, but we want to make sure that this @@ -680,7 +680,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { assert_eq!(kind, "lifetime"); let provided = force_infer_lt.expect("lifetimes ought to have been inferred"); - Self::generic_arg_mismatch_err(tcx.sess, provided, kind); + Self::generic_arg_mismatch_err(tcx, provided, kind); } break; @@ -911,7 +911,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ConvertedBindingKind::Constraint(bounds) } }; - ConvertedBinding { item_name: binding.ident, kind, span: binding.span } + ConvertedBinding { + item_name: binding.ident, + kind, + span: tcx.hir().span(binding.hir_id), + } }) .collect(); @@ -2485,7 +2489,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!( @@ -2505,7 +2509,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // Only emit the first error to avoid overloading the user with error messages. if let [binding, ..] = segment.generic_args().bindings { has_err = true; - Self::prohibit_assoc_ty_binding(self.tcx(), binding.span); + Self::prohibit_assoc_ty_binding(self.tcx(), self.tcx().hir().span(binding.hir_id)); } } has_err @@ -2539,7 +2543,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/src/librustc_typeck/check/_match.rs b/src/librustc_typeck/check/_match.rs index 9e23f5df3c6a8..97de0dc03ab85 100644 --- a/src/librustc_typeck/check/_match.rs +++ b/src/librustc_typeck/check/_match.rs @@ -254,7 +254,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } if let Local(hir::Local { ty: Some(_), pat, .. }) = node { - return Some((pat.span, "expected because of this assignment".to_string())); + let span = self.tcx.hir().span(pat.hir_id); + return Some((span, "expected because of this assignment".to_string())); } None } @@ -300,7 +301,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else if let Some(stmt) = block.stmts.last() { // possibly incorrect trailing `;` in the else arm remove_semicolon = self.could_remove_semicolon(block, then_ty); - stmt.span + self.tcx.hir().span(stmt.hir_id) } else { // empty block; point at its entirety // Avoid overlapping spans that aren't as readable: @@ -347,7 +348,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else if let Some(stmt) = block.stmts.last() { // possibly incorrect trailing `;` in the else arm remove_semicolon = remove_semicolon.or(self.could_remove_semicolon(block, else_ty)); - stmt.span + self.tcx.hir().span(stmt.hir_id) } else { // empty block; point at its entirety outer_sp = None; // same as in `error_sp`; cleanup output diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs index 4e97ba41dcbb3..a04a5e00d3fbb 100644 --- a/src/librustc_typeck/check/compare_method.rs +++ b/src/librustc_typeck/check/compare_method.rs @@ -595,8 +595,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 @@ -605,7 +609,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(); @@ -625,11 +629,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/src/librustc_typeck/check/expr.rs b/src/librustc_typeck/check/expr.rs index 1eaa5a6c31e20..d666325394366 100644 --- a/src/librustc_typeck/check/expr.rs +++ b/src/librustc_typeck/check/expr.rs @@ -795,7 +795,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)) } @@ -823,8 +824,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()) } @@ -1184,17 +1186,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for field in ast_fields { let ident = tcx.adjust_ident(field.ident, variant.def_id); let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) { - seen_fields.insert(ident, field.span); + let field_span = self.tcx.hir().span(field.hir_id); + seen_fields.insert(ident, field_span); self.write_field_index(field.hir_id, i); // We don't look at stability attributes on // struct-like enums (yet...), but it's definitely not // a bug to have constructed one. if adt_kind != AdtKind::Enum { - tcx.check_stability(v_field.did, Some(expr_id), field.span); + tcx.check_stability(v_field.did, Some(expr_id), field_span); } - self.field_ty(field.span, v_field, substs) + self.field_ty(field_span, v_field, substs) } else { error_happened = true; if let Some(prev_span) = seen_fields.get(&ident) { diff --git a/src/librustc_typeck/check/generator_interior.rs b/src/librustc_typeck/check/generator_interior.rs index ce376a08ea604..2c388a71d4d54 100644 --- a/src/librustc_typeck/check/generator_interior.rs +++ b/src/librustc_typeck/check/generator_interior.rs @@ -223,7 +223,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.tables.borrow().pat_ty(pat); - self.record(ty, Some(scope), None, pat.span); + let span = self.fcx.tcx.hir().span(pat.hir_id); + self.record(ty, Some(scope), None, span); } } diff --git a/src/librustc_typeck/check/intrinsic.rs b/src/librustc_typeck/check/intrinsic.rs index 3ec6973a17d56..5b23a7e262724 100644 --- a/src/librustc_typeck/check/intrinsic.rs +++ b/src/librustc_typeck/check/intrinsic.rs @@ -27,8 +27,9 @@ fn equate_intrinsic_type<'tcx>( 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") + let it_span = tcx.hir().span(it.hir_id); + struct_span_err!(tcx.sess, it_span, E0622, "intrinsic must be a function") + .span_label(it_span, "expected a function") .emit(); return; } @@ -62,7 +63,8 @@ fn equate_intrinsic_type<'tcx>( safety, abi, ))); - let cause = ObligationCause::new(it.span, it.hir_id, ObligationCauseCode::IntrinsicType); + let it_span = tcx.hir().span(it.hir_id); + let cause = ObligationCause::new(it_span, it.hir_id, ObligationCauseCode::IntrinsicType); require_same_types(tcx, &cause, tcx.mk_fn_ptr(tcx.fn_sig(def_id)), fty); } @@ -117,14 +119,15 @@ 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 => { + let it_span = tcx.hir().span(it.hir_id); struct_span_err!( tcx.sess, - it.span, + it_span, E0092, "unrecognized atomic operation function: `{}`", op ) - .span_label(it.span, "unrecognized atomic operation") + .span_label(it_span, "unrecognized atomic operation") .emit(); return; } @@ -350,14 +353,15 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { "count_code_region" => (0, vec![tcx.types.u32], tcx.mk_unit()), ref other => { + let it_span = tcx.hir().span(it.hir_id); struct_span_err!( tcx.sess, - it.span, + it_span, E0093, "unrecognized intrinsic function: `{}`", *other ) - .span_label(it.span, "unrecognized intrinsic") + .span_label(it_span, "unrecognized intrinsic") .emit(); return; } @@ -427,9 +431,10 @@ pub fn check_platform_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) (2, params, param(1)) } Err(_) => { + let it_span = tcx.hir().span(it.hir_id); struct_span_err!( tcx.sess, - it.span, + it_span, E0439, "invalid `simd_shuffle`, needs length: `{}`", name @@ -440,7 +445,8 @@ pub fn check_platform_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) }, _ => { 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/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs index 67bdd04d3715c..73dbcc3a550fc 100644 --- a/src/librustc_typeck/check/method/suggest.rs +++ b/src/librustc_typeck/check/method/suggest.rs @@ -1322,7 +1322,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; } @@ -1333,12 +1333,13 @@ impl intravisit::Visitor<'tcx> for UsePlacementFinder<'tcx> { // Find a `use` statement. for item_id in module.item_ids { let item = self.tcx.hir().expect_item(item_id.id); + let item_span = self.tcx.hir().span(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; } @@ -1347,11 +1348,11 @@ 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. if item.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 item.attrs { diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 1594d65e9bdee..1715cae7929b4 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -986,10 +986,10 @@ fn typeck_tables_of_with_fallback<'tcx>( } let id = tcx.hir().as_local_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); @@ -1011,7 +1011,7 @@ fn typeck_tables_of_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); @@ -1131,8 +1131,9 @@ fn typeck_tables_of_with_fallback<'tcx>( tables } -fn check_abi(tcx: TyCtxt<'_>, span: Span, abi: Abi) { +fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, abi: Abi) { if !tcx.sess.target.target.is_abi_supported(abi) { + let span = tcx.hir().span(hir_id); struct_span_err!( tcx.sess, span, @@ -1207,7 +1208,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 {}", @@ -1220,10 +1222,11 @@ 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.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)); } debug!( @@ -1242,7 +1245,6 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> { _: intravisit::FnKind<'tcx>, _: &'tcx hir::FnDecl<'tcx>, _: hir::BodyId, - _: Span, _: hir::HirId, ) { } @@ -1328,7 +1330,7 @@ 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(VaListTypeLangItem, Some(span)); let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span)); @@ -1349,7 +1351,8 @@ 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_locals { - fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType); + let pat_span = fcx.tcx.hir().span(param.pat.hir_id); + fcx.require_type_is_sized(param_ty, pat_span, traits::SizedArgumentType); } fcx.write_ty(param.hir_id, param_ty); @@ -1540,33 +1543,33 @@ fn check_fn<'a, 'tcx>( (fcx, gen_ty) } -fn check_struct(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) { +fn check_struct(tcx: TyCtxt<'_>, id: hir::HirId) { let def_id = tcx.hir().local_def_id(id); 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, id); if def.repr.simd() { - check_simd(tcx, span, def_id); + check_simd(tcx, id, def_id); } - check_transparent(tcx, span, def); - check_packed(tcx, span, def); + check_transparent(tcx, id, def); + check_packed(tcx, id, def); } -fn check_union(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) { +fn check_union(tcx: TyCtxt<'_>, id: hir::HirId) { let def_id = tcx.hir().local_def_id(id); 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, id); + check_transparent(tcx, id, def); + check_union_fields(tcx, id, def_id); + check_packed(tcx, id, def); } /// When the `#![feature(untagged_unions)]` gate is active, /// check that the fields of the `union` does not contain fields that need dropping. -fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool { +fn check_union_fields(tcx: TyCtxt<'_>, id: hir::HirId, 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()); @@ -1589,6 +1592,7 @@ fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> b } } } else { + let span = tcx.hir().span(id); span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind); } true @@ -1598,23 +1602,20 @@ fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> b /// projections that would result in "inheriting lifetimes". fn check_opaque<'tcx>( tcx: TyCtxt<'tcx>, - def_id: LocalDefId, + hir_id: hir::HirId, substs: SubstsRef<'tcx>, - span: Span, origin: &hir::OpaqueTyOrigin, ) { - check_opaque_for_inheriting_lifetimes(tcx, def_id, span); - check_opaque_for_cycles(tcx, def_id, substs, span, origin); + check_opaque_for_inheriting_lifetimes(tcx, hir_id); + check_opaque_for_cycles(tcx, hir_id, substs, origin); } /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result /// in "inheriting lifetimes". -fn check_opaque_for_inheriting_lifetimes(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) { - let item = tcx.hir().expect_item(tcx.hir().as_local_hir_id(def_id)); - debug!( - "check_opaque_for_inheriting_lifetimes: def_id={:?} span={:?} item={:?}", - def_id, span, item - ); +fn check_opaque_for_inheriting_lifetimes(tcx: TyCtxt<'tcx>, hir_id: hir::HirId) { + let def_id = tcx.hir().local_def_id(hir_id); + let item = tcx.hir().expect_item(hir_id); + debug!("check_opaque_for_inheriting_lifetimes: def_id={:?} item={:?}", def_id, item); #[derive(Debug)] struct ProhibitOpaqueVisitor<'tcx> { @@ -1685,6 +1686,7 @@ fn check_opaque_for_inheriting_lifetimes(tcx: TyCtxt<'tcx>, def_id: LocalDefId, _ => unreachable!(), }; + let span = tcx.hir().span(hir_id); let mut err = struct_span_err!( tcx.sess, span, @@ -1739,7 +1741,8 @@ fn get_owner_return_paths( /// /// 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>, def_id: LocalDefId, hir_id: hir::HirId) { + let span = tcx.hir().span(hir_id); let mut err = struct_span_err!(tcx.sess, span, E0720, "cannot resolve opaque type"); let mut label = false; @@ -1815,9 +1818,10 @@ fn opaque_type_cycle_error(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) { fn binding_opaque_type_cycle_error( tcx: TyCtxt<'tcx>, def_id: LocalDefId, - span: Span, + hir_id: hir::HirId, partially_expanded_type: Ty<'tcx>, ) { + let span = tcx.hir().span(hir_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 the owner that declared this `impl Trait` type. @@ -1833,7 +1837,10 @@ fn binding_opaque_type_cycle_error( source: hir::LocalSource::Normal, .. }) => { - err.span_label(pat.span, "this binding might not have a concrete type"); + err.span_label( + tcx.hir().span(pat.hir_id), + "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", @@ -1871,7 +1878,8 @@ fn binding_opaque_type_cycle_error( err.emit(); } -fn async_opaque_type_cycle_error(tcx: TyCtxt<'tcx>, span: Span) { +fn async_opaque_type_cycle_error(tcx: TyCtxt<'tcx>, hir_id: hir::HirId) { + let span = tcx.hir().span(hir_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`") @@ -1881,19 +1889,19 @@ fn async_opaque_type_cycle_error(tcx: TyCtxt<'tcx>, span: Span) { /// Checks that an opaque type does not contain cycles. fn check_opaque_for_cycles<'tcx>( tcx: TyCtxt<'tcx>, - def_id: LocalDefId, + hir_id: hir::HirId, substs: SubstsRef<'tcx>, - span: Span, origin: &hir::OpaqueTyOrigin, ) { + let def_id = tcx.hir().local_def_id(hir_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, hir_id), hir::OpaqueTyOrigin::Binding => { - binding_opaque_type_cycle_error(tcx, def_id, span, partially_expanded_type) + binding_opaque_type_cycle_error(tcx, def_id, hir_id, partially_expanded_type) } - _ => opaque_type_cycle_error(tcx, def_id, span), + _ => opaque_type_cycle_error(tcx, def_id, hir_id), } } } @@ -1918,20 +1926,20 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { hir::ItemKind::Static(..) => { let def_id = tcx.hir().local_def_id(it.hir_id); tcx.ensure().typeck_tables_of(def_id); - maybe_check_static_with_link_section(tcx, def_id, it.span); + maybe_check_static_with_link_section(tcx, it.hir_id); } hir::ItemKind::Const(..) => { tcx.ensure().typeck_tables_of(tcx.hir().local_def_id(it.hir_id)); } hir::ItemKind::Enum(ref enum_definition, _) => { - check_enum(tcx, it.span, &enum_definition.variants, it.hir_id); + check_enum(tcx, &enum_definition.variants, it.hir_id); } hir::ItemKind::Fn(..) => {} // entirely within check_item_body hir::ItemKind::Impl { ref items, .. } => { debug!("ItemKind::Impl {} with id {}", it.ident, it.hir_id); let impl_def_id = tcx.hir().local_def_id(it.hir_id); if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) { - check_impl_items_against_trait(tcx, it.span, impl_def_id, impl_trait_ref, items); + check_impl_items_against_trait(tcx, it.hir_id, impl_def_id, impl_trait_ref, items); let trait_def_id = impl_trait_ref.def_id; check_on_unimplemented(tcx, trait_def_id, it); } @@ -1949,16 +1957,16 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { } } hir::ItemKind::Struct(..) => { - check_struct(tcx, it.hir_id, it.span); + check_struct(tcx, it.hir_id); } hir::ItemKind::Union(..) => { - check_union(tcx, it.hir_id, it.span); + check_union(tcx, it.hir_id); } hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => { let def_id = tcx.hir().local_def_id(it.hir_id); let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id()); - check_opaque(tcx, def_id, substs, it.span, &origin); + check_opaque(tcx, it.hir_id, substs, &origin); } hir::ItemKind::TyAlias(..) => { let def_id = tcx.hir().local_def_id(it.hir_id); @@ -1967,7 +1975,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(ref m) => { - check_abi(tcx, it.span, m.abi); + check_abi(tcx, it.hir_id, m.abi); if m.abi == Abi::RustIntrinsic { for item in m.items { @@ -1981,6 +1989,7 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { for item in m.items { let generics = tcx.generics_of(tcx.hir().local_def_id(item.hir_id)); let own_counts = generics.own_counts(); + let item_span = tcx.hir().span(item.hir_id); if generics.params.len() - own_counts.lifetimes != 0 { let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) { (_, 0) => ("type", "types", Some("u32")), @@ -1991,12 +2000,12 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { }; 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. @@ -2011,7 +2020,7 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { } if let hir::ForeignItemKind::Fn(ref fn_decl, _, _) = item.kind { - require_c_abi_if_c_variadic(tcx, fn_decl, m.abi, item.span); + require_c_abi_if_c_variadic(tcx, fn_decl, m.abi, item_span); } } } @@ -2020,12 +2029,14 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { } } -fn maybe_check_static_with_link_section(tcx: TyCtxt<'_>, id: LocalDefId, span: Span) { +fn maybe_check_static_with_link_section(tcx: TyCtxt<'_>, hir_id: hir::HirId) { // Only restricted on wasm32 target for now if !tcx.sess.opts.target_triple.triple().starts_with("wasm32") { return; } + let id = tcx.hir().local_def_id(hir_id); + // If `#[link_section]` is missing, then nothing to verify let attrs = tcx.codegen_fn_attrs(id); if attrs.link_section.is_none() { @@ -2043,6 +2054,7 @@ fn maybe_check_static_with_link_section(tcx: TyCtxt<'_>, id: LocalDefId, span: S match tcx.const_eval_poly(id.to_def_id()) { Ok(ConstValue::ByRef { alloc, .. }) => { if alloc.relocations().len() != 0 { + let span = tcx.hir().span(hir_id); let msg = "statics with a custom `#[link_section]` must be a \ simple list of bytes on the wasm target with no \ extra levels of indirection such as references"; @@ -2065,15 +2077,16 @@ fn report_forbidden_specialization( impl_item: &hir::ImplItem<'_>, parent_impl: DefId, ) { + let impl_item_span = tcx.hir().span(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) => { @@ -2159,13 +2172,11 @@ fn check_specialization_validity<'tcx>( fn check_impl_items_against_trait<'tcx>( tcx: TyCtxt<'tcx>, - full_impl_span: Span, + full_impl_id: hir::HirId, impl_id: LocalDefId, impl_trait_ref: ty::TraitRef<'tcx>, impl_item_refs: &[hir::ImplItemRef<'_>], ) { - let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span); - // 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. @@ -2178,7 +2189,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(tcx.hir().impl_item(first_item_ref.id).hir_id); struct_span_err!( tcx.sess, first_item_span, @@ -2213,6 +2224,7 @@ fn check_impl_items_against_trait<'tcx>( // Check that impl definition matches trait definition if let Some(ty_trait_item) = ty_trait_item { + let impl_item_span = tcx.hir().span(impl_item.hir_id); match impl_item.kind { hir::ImplItemKind::Const(..) => { // Find associated const definition. @@ -2220,21 +2232,21 @@ 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, ); } else { let mut err = 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, impl_trait_ref.print_only_trait_path() ); - err.span_label(impl_item.span, "does not match trait"); + err.span_label(impl_item_span, "does not match trait"); // We can only get the spans from local trait definition // Same for E0324 and E0325 if let Some(trait_span) = tcx.hir().span_if_local(ty_trait_item.def_id) { @@ -2249,7 +2261,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, @@ -2257,14 +2269,14 @@ fn check_impl_items_against_trait<'tcx>( } else { let mut err = 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, impl_trait_ref.print_only_trait_path() ); - 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) = opt_trait_span { err.span_label(trait_span, "item in trait"); } @@ -2277,7 +2289,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, @@ -2285,14 +2297,14 @@ fn check_impl_items_against_trait<'tcx>( } else { let mut err = 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, impl_trait_ref.print_only_trait_path() ); - 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) = opt_trait_span { err.span_label(trait_span, "item in trait"); } @@ -2329,6 +2341,8 @@ fn check_impl_items_against_trait<'tcx>( } if !missing_items.is_empty() { + let full_impl_span = tcx.hir().span(full_impl_id); + let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span); missing_items_err(tcx, impl_span, &missing_items, full_impl_span); } } @@ -2535,7 +2549,8 @@ fn suggestion_signature(assoc: &ty::AssocItem, tcx: TyCtxt<'_>) -> String { /// 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. -fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bool { +fn check_representable(tcx: TyCtxt<'_>, item_hir_id: hir::HirId) -> bool { + let item_def_id = tcx.hir().local_def_id(item_hir_id); let rty = tcx.type_of(item_def_id); // Check that it is possible to represent this type. This call identifies @@ -2543,7 +2558,7 @@ fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bo // 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, item_hir_id) { Representability::SelfRecursive(spans) => { recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans); return false; @@ -2553,17 +2568,19 @@ fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bo true } -pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) { +pub fn check_simd(tcx: TyCtxt<'_>, hir_id: hir::HirId, 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.hir().span(hir_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.hir().span(hir_id); struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous") .span_label(sp, "SIMD elements must have the same type") .emit(); @@ -2573,6 +2590,7 @@ pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) { ty::Param(_) => { /* struct(T, T, T, T) is ok */ } _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ } _ => { + let sp = tcx.hir().span(hir_id); struct_span_err!( tcx.sess, sp, @@ -2587,7 +2605,7 @@ pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) { } } -fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) { +fn check_packed(tcx: TyCtxt<'_>, id: hir::HirId, def: &ty::AdtDef) { let repr = def.repr; if repr.packed() { for attr in tcx.get_attrs(def.did).iter() { @@ -2595,6 +2613,7 @@ 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.hir().span(id); struct_span_err!( tcx.sess, sp, @@ -2608,6 +2627,7 @@ fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) { } } if repr.align.is_some() { + let sp = tcx.hir().span(id); struct_span_err!( tcx.sess, sp, @@ -2617,6 +2637,7 @@ 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.hir().span(id); let mut err = struct_span_err!( tcx.sess, sp, @@ -2735,13 +2756,14 @@ fn bad_non_zero_sized_fields<'tcx>( err.emit(); } -fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) { +fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, hir_id: hir::HirId, adt: &'tcx ty::AdtDef) { if !adt.repr.transparent() { return; } - let sp = tcx.sess.source_map().guess_head_span(sp); if adt.is_union() && !tcx.features().transparent_unions { + let sp = tcx.hir().span(hir_id); + let sp = tcx.sess.source_map().guess_head_span(sp); feature_err( &tcx.sess.parse_sess, sym::transparent_unions, @@ -2752,6 +2774,8 @@ fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) { } if adt.variants.len() != 1 { + let sp = tcx.hir().span(hir_id); + let sp = tcx.sess.source_map().guess_head_span(sp); bad_variant_count(tcx, adt, sp, adt.did); if adt.variants.is_empty() { // Don't bother checking the fields. No variants (and thus no fields) exist. @@ -2775,6 +2799,8 @@ fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) { field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None }); let non_zst_count = non_zst_fields.clone().count(); if non_zst_count != 1 { + let sp = tcx.hir().span(hir_id); + let sp = tcx.sess.source_map().guess_head_span(sp); bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp); } for (span, zst, align1) in field_infos { @@ -2793,12 +2819,7 @@ fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty::AdtDef) { } #[allow(trivial_numeric_casts)] -pub fn check_enum<'tcx>( - tcx: TyCtxt<'tcx>, - sp: Span, - vs: &'tcx [hir::Variant<'tcx>], - id: hir::HirId, -) { +pub fn check_enum<'tcx>(tcx: TyCtxt<'tcx>, vs: &'tcx [hir::Variant<'tcx>], id: hir::HirId) { let def_id = tcx.hir().local_def_id(id); let def = tcx.adt_def(def_id); def.destructor(tcx); // force the destructor to be evaluated @@ -2806,6 +2827,7 @@ pub fn check_enum<'tcx>( if vs.is_empty() { let attributes = tcx.get_attrs(def_id.to_def_id()); if let Some(attr) = attr::find_by_name(&attributes, sym::repr) { + let sp = tcx.hir().span(id); struct_span_err!( tcx.sess, attr.span, @@ -2820,6 +2842,7 @@ pub 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.hir().span(id); feature_err( &tcx.sess.parse_sess, sym::repr128, @@ -2848,6 +2871,7 @@ pub 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.hir().span(id); let mut err = struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified"); err.emit(); @@ -2865,10 +2889,10 @@ pub fn check_enum<'tcx>( Some(ref expr) => tcx.hir().span(expr.hir_id), None => tcx.hir().span(variant_i_hir_id), }; - let span = match v.disr_expr { - Some(ref expr) => tcx.hir().span(expr.hir_id), - None => v.span, - }; + let span = tcx.hir().span(match v.disr_expr { + Some(ref expr) => expr.hir_id, + None => v.id, + }); struct_span_err!( tcx.sess, span, @@ -2883,8 +2907,8 @@ pub fn check_enum<'tcx>( disr_vals.push(discr); } - check_representable(tcx, sp, def_id); - check_transparent(tcx, sp, def); + check_representable(tcx, id); + check_transparent(tcx, id, def); } fn report_unexpected_variant_res(tcx: TyCtxt<'_>, res: Res, span: Span) { @@ -3938,9 +3962,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Account for `foo.bar::()`. .map(|arg| { // Skip the closing `>`. - tcx.sess - .source_map() - .next_point(tcx.sess.source_map().next_point(arg.span())) + tcx.sess.source_map().next_point( + tcx.sess.source_map().next_point(tcx.hir().span(arg.id())), + ) }) .unwrap_or(*span), &args[1..], // Skip the receiver. @@ -4565,7 +4589,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. @@ -4619,7 +4644,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 span = self.tcx.hir().span(stmt.hir_id); + self.warn_if_unreachable(stmt.hir_id, span, "statement"); // Hide the outer diverging and `has_errors` flags. let old_diverges = self.diverges.replace(Diverges::Maybe); @@ -4654,7 +4680,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 span = self.tcx.hir().span(blk.hir_id); + self.demand_suptype(span, unit, ty); } } @@ -4679,7 +4706,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Some(match &arm.body.kind { // Point at the tail expression when possible. hir::ExprKind::Block(block, _) => { - block.expr.as_ref().map(|e| e.span).unwrap_or(block.span) + let span = self.tcx.hir().span(block.hir_id); + block.expr.as_ref().map(|e| e.span).unwrap_or(span) } _ => arm.body.span, }) @@ -4722,7 +4750,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 span = self.tcx.hir().span(blk.hir_id); + let coerce_to_ty = expected.coercion_target_type(self, span); let coerce = if blk.targeted_by_break { CoerceMany::new(coerce_to_ty) } else { @@ -4770,7 +4799,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 = span; let mut fn_span = None; if let Some((decl, ident)) = self.get_parent_fn_decl(blk.hir_id) { let ret_sp = decl.output.span(); @@ -4778,7 +4807,7 @@ 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 { + if block_sp == span { sp = ret_sp; fn_span = Some(ident.span); } @@ -4830,7 +4859,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 span = self.tcx.hir().span(block.hir_id); + return Some(span); } } _ => {} @@ -5407,7 +5437,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { return None; } - let original_span = original_sp(last_stmt.span, blk.span); + let last_stmt_span = self.tcx.hir().span(last_stmt.hir_id); + let blk_span = self.tcx.hir().span(blk.hir_id); + let original_span = original_sp(last_stmt_span, blk_span); Some(original_span.with_lo(original_span.hi() - BytePos(1))) } diff --git a/src/librustc_typeck/check/pat.rs b/src/librustc_typeck/check/pat.rs index ea47ae68ce7d3..06878a036a756 100644 --- a/src/librustc_typeck/check/pat.rs +++ b/src/librustc_typeck/check/pat.rs @@ -157,8 +157,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) { debug!("check_pat(pat={:?},expected={:?},def_bm={:?})", pat, expected, def_bm); + let pat_span = self.tcx.hir().span(pat.hir_id); let path_res = match &pat.kind { - PatKind::Path(qpath) => Some(self.resolve_ty_and_res_ufcs(qpath, pat.hir_id, pat.span)), + PatKind::Path(qpath) => Some(self.resolve_ty_and_res_ufcs(qpath, pat.hir_id, pat_span)), _ => None, }; let adjust_mode = self.calc_adjust_mode(pat, path_res.map(|(res, ..)| res)); @@ -166,8 +167,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ty = match pat.kind { PatKind::Wild => expected, - PatKind::Lit(lt) => self.check_pat_lit(pat.span, lt, expected, ti), - PatKind::Range(lhs, rhs, _) => self.check_pat_range(pat.span, lhs, rhs, expected, ti), + PatKind::Lit(lt) => self.check_pat_lit(pat_span, lt, expected, ti), + PatKind::Range(lhs, rhs, _) => self.check_pat_range(pat_span, lhs, rhs, expected, ti), PatKind::Binding(ba, var_id, _, sub) => { self.check_pat_ident(pat, ba, var_id, sub, expected, def_bm, ti) } @@ -186,14 +187,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected } PatKind::Tuple(elements, ddpos) => { - self.check_pat_tuple(pat.span, elements, ddpos, expected, def_bm, ti) + self.check_pat_tuple(pat_span, elements, ddpos, expected, def_bm, ti) } - PatKind::Box(inner) => self.check_pat_box(pat.span, inner, expected, def_bm, ti), + PatKind::Box(inner) => self.check_pat_box(pat_span, inner, expected, def_bm, ti), PatKind::Ref(inner, mutbl) => { self.check_pat_ref(pat, inner, mutbl, expected, def_bm, ti) } PatKind::Slice(before, slice, after) => { - self.check_pat_slice(pat.span, before, slice, after, expected, def_bm, ti) + self.check_pat_slice(pat_span, before, slice, after, expected, def_bm, ti) } }; @@ -538,7 +539,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`, @@ -548,7 +550,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(_) => { @@ -556,12 +558,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 { @@ -606,10 +608,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let binding_parent = tcx.hir().get(binding_parent_id); debug!("inner {:?} pat {:?} parent {:?}", inner, pat, binding_parent); match binding_parent { - hir::Node::Param(hir::Param { span, .. }) => { - if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner.span) { + hir::Node::Param(hir::Param { hir_id, .. }) => { + let span = tcx.hir().span(*hir_id); + let inner_span = self.tcx.hir().span(inner.hir_id); + if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner_span) { err.span_suggestion( - *span, + span, &format!("did you mean `{}`", snippet), format!(" &{}", expected), Applicability::MachineApplicable, @@ -618,9 +622,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, @@ -682,7 +688,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) { @@ -709,7 +716,7 @@ 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); + report_unexpected_variant_res(tcx, res, self.tcx.hir().span(pat.hir_id)); return tcx.ty_error(); } Res::SelfCtor(..) @@ -724,12 +731,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, segments, ti.parent_pat); + self.emit_bad_pat_path(err, pat_span, res, pat_res, segments, ti.parent_pat); } pat_ty } @@ -792,10 +800,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.check_pat(&pat, tcx.ty_error(), def_bm, TopInfo { parent_pat, ..ti }); } }; + let pat_span = self.tcx.hir().span(pat.hir_id); let report_unexpected_res = |res: Res| { let sm = tcx.sess.source_map(); let path_str = sm - .span_to_snippet(sm.span_until_char(pat.span, '(')) + .span_to_snippet(sm.span_until_char(pat_span, '(')) .map_or(String::new(), |s| format!(" `{}`", s.trim_end())); let msg = format!( "expected tuple struct or tuple variant, found {}{}", @@ -803,17 +812,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(); @@ -821,7 +830,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(); @@ -830,7 +839,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(); @@ -855,7 +864,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 @@ -872,14 +881,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(); } @@ -958,7 +968,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // | // L | let A((x, y)) = A((1, 2)); // | ^ ^ - [first, ..] => (first.span.shrink_to_lo(), subpats.last().unwrap().span), + [first, ..] => ( + self.tcx.hir().span(first.hir_id).shrink_to_lo(), + self.tcx.hir().span(subpats.last().unwrap().hir_id), + ), }; err.multipart_suggestion( "missing parenthesis", @@ -1027,9 +1040,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. @@ -1047,7 +1061,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) => { @@ -1100,14 +1114,14 @@ 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() { - self.error_unmentioned_fields(pat.span, &unmentioned_fields, variant); + self.error_unmentioned_fields(pat_span, &unmentioned_fields, variant); } no_field_errors } @@ -1115,13 +1129,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 @@ -1274,9 +1289,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); @@ -1300,7 +1316,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. @@ -1311,13 +1328,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/src/librustc_typeck/check/regionck.rs b/src/librustc_typeck/check/regionck.rs index d3bccaaa3e4b9..66df5c958eccd 100644 --- a/src/librustc_typeck/check/regionck.rs +++ b/src/librustc_typeck/check/regionck.rs @@ -321,7 +321,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; let _ = dropck::check_drop_obligations(self, typ, span, body_id); @@ -349,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!( @@ -367,6 +367,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. @@ -564,8 +565,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); } @@ -576,13 +577,14 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { fn link_pattern(&self, discr_cmt: mc::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.tables.extract_binding_mode(self.tcx.sess, *hir_id, *span) + mc.tables.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/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index d1a86a7ee89a8..f10c95d836db8 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -110,7 +110,8 @@ pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) { .impl_trait_ref(tcx.hir().local_def_id(item.hir_id)) .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id)); if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) { - let sp = of_trait.as_ref().map(|t| t.path.span).unwrap_or(item.span); + let item_span = tcx.hir().span(item.hir_id); + let sp = of_trait.as_ref().map(|t| t.path.span).unwrap_or(item_span); let mut err = tcx.sess.struct_span_err(sp, "impls of auto traits cannot be default"); err.span_labels(defaultness_span, "default because of this"); @@ -186,13 +187,14 @@ pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) { pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: LocalDefId) { let hir_id = tcx.hir().as_local_hir_id(def_id); let trait_item = tcx.hir().expect_trait_item(hir_id); + let trait_item_span = tcx.hir().span(trait_item.hir_id); let method_sig = match trait_item.kind { hir::TraitItemKind::Fn(ref sig, _) => Some(sig), _ => 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, trait_item_span, method_sig); } fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool { @@ -260,13 +262,14 @@ fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: LocalDefId) { let hir_id = tcx.hir().as_local_hir_id(def_id); let impl_item = tcx.hir().expect_impl_item(hir_id); + let impl_item_span = tcx.hir().span(impl_item.hir_id); let method_sig = match impl_item.kind { hir::ImplItemKind::Fn(ref sig, _) => Some(sig), _ => None, }; - check_associated_item(tcx, impl_item.hir_id, impl_item.span, method_sig); + check_associated_item(tcx, impl_item.hir_id, impl_item_span, method_sig); } fn check_associated_item( @@ -323,7 +326,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(item.hir_id); + for_id(tcx, item.hir_id, item_span) } fn for_id(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) -> CheckWfFcxBuilder<'_> { @@ -354,6 +358,7 @@ fn check_type_defn<'tcx, F>( ) where F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec>, { + let item_span = tcx.hir().span(item.hir_id); for_item(tcx, item).with_fcx(|fcx, fcx_tcx| { let variants = lookup_fields(fcx); let def_id = fcx.tcx.hir().local_def_id(item.hir_id); @@ -369,7 +374,7 @@ fn check_type_defn<'tcx, F>( if ty.needs_infer() { 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 { @@ -428,7 +433,7 @@ fn check_type_defn<'tcx, F>( } } - check_where_clauses(tcx, fcx, item.span, def_id.to_def_id(), None); + check_where_clauses(tcx, fcx, item_span, def_id.to_def_id(), None); // No implied bounds in a struct definition. vec![] @@ -455,8 +460,9 @@ fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) { } } + let item_span = tcx.hir().span(item.hir_id); for_item(tcx, item).with_fcx(|fcx, _| { - check_where_clauses(tcx, fcx, item.span, trait_def_id.to_def_id(), None); + check_where_clauses(tcx, fcx, item_span, trait_def_id.to_def_id(), None); check_associated_type_defaults(fcx, trait_def_id.to_def_id()); vec![] @@ -561,10 +567,11 @@ fn check_associated_type_defaults(fcx: &FnCtxt<'_, '_>, trait_def_id: DefId) { } fn check_item_fn(tcx: TyCtxt<'_>, item: &hir::Item<'_>) { + let item_span = tcx.hir().span(item.hir_id); for_item(tcx, item).with_fcx(|fcx, tcx| { let def_id = fcx.tcx.hir().local_def_id(item.hir_id); let sig = fcx.tcx.fn_sig(def_id); - let sig = fcx.normalize_associated_types_in(item.span, &sig); + let sig = fcx.normalize_associated_types_in(item_span, &sig); let mut implied_bounds = vec![]; let hir_sig = match &item.kind { ItemKind::Fn(sig, ..) => sig, @@ -620,6 +627,7 @@ fn check_impl<'tcx>( ) { debug!("check_impl: {:?}", item); + let item_span = tcx.hir().span(item.hir_id); for_item(tcx, item).with_fcx(|fcx, tcx| { let item_def_id = fcx.tcx.hir().local_def_id(item.hir_id); @@ -645,7 +653,7 @@ 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 self_ty = fcx.normalize_associated_types_in(item_span, &self_ty); fcx.register_wf_obligation( self_ty.into(), ast_self_ty.span, @@ -654,9 +662,9 @@ fn check_impl<'tcx>( } } - check_where_clauses(tcx, fcx, item.span, item_def_id.to_def_id(), None); + 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) }); } @@ -1220,7 +1228,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), } } } @@ -1326,10 +1334,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .iter() .map(|field| { 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.span, &field_ty); + let span = self.tcx.hir().span(field.hir_id); + 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.span } + AdtField { ty: field_ty, span } }) .collect(); AdtVariant { fields, explicit_discr: None } diff --git a/src/librustc_typeck/check/writeback.rs b/src/librustc_typeck/check/writeback.rs index 4704d8fc7666f..523277a048a9d 100644 --- a/src/librustc_typeck/check/writeback.rs +++ b/src/librustc_typeck/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) { @@ -281,15 +282,17 @@ impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { } fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) { - self.visit_node_id(b.span, b.hir_id); + let span = self.tcx().hir().span(b.hir_id); + self.visit_node_id(span, b.hir_id); intravisit::walk_block(self, b); } fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { + let span = self.tcx().hir().span(p.hir_id); match p.kind { hir::PatKind::Binding(..) => { let tables = self.fcx.tables.borrow(); - if let Some(bm) = tables.extract_binding_mode(self.tcx().sess, p.hir_id, p.span) { + if let Some(bm) = tables.extract_binding_mode(self.tcx().sess, p.hir_id, span) { self.tables.pat_binding_modes_mut().insert(p.hir_id, bm); } } @@ -301,16 +304,17 @@ impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { _ => {} }; - self.visit_pat_adjustments(p.span, p.hir_id); + self.visit_pat_adjustments(span, p.hir_id); - self.visit_node_id(p.span, p.hir_id); + self.visit_node_id(span, p.hir_id); intravisit::walk_pat(self, p); } fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { intravisit::walk_local(self, l); - let var_ty = self.fcx.local_ty(l.span, l.hir_id).decl_ty; - let var_ty = self.resolve(&var_ty, &l.span); + let span = self.tcx().hir().span(l.hir_id); + let var_ty = self.fcx.local_ty(span, l.hir_id).decl_ty; + let var_ty = self.resolve(&var_ty, &span); self.write_ty_to_tables(l.hir_id, var_ty); } diff --git a/src/librustc_typeck/check_unused.rs b/src/librustc_typeck/check_unused.rs index 81daf064bb368..560ea0cdc6b57 100644 --- a/src/librustc_typeck/check_unused.rs +++ b/src/librustc_typeck/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(item.hir_id); + if item.vis.node.is_pub() || item_span.is_dummy() { return; } if let hir::ItemKind::Use(ref path, _) = item.kind { @@ -213,9 +214,10 @@ impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for CollectExternCrateVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &hir::Item<'_>) { if let hir::ItemKind::ExternCrate(orig_name) = item.kind { let extern_crate_def_id = self.tcx.hir().local_def_id(item.hir_id); + let item_span = self.tcx.hir().span(item.hir_id); self.crates_to_lint.push(ExternCrateToLint { def_id: extern_crate_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/src/librustc_typeck/coherence/inherent_impls.rs b/src/librustc_typeck/coherence/inherent_impls.rs index 93ee87f6c572e..8b798203eb096 100644 --- a/src/librustc_typeck/coherence/inherent_impls.rs +++ b/src/librustc_typeck/coherence/inherent_impls.rs @@ -50,6 +50,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { }; let def_id = self.tcx.hir().local_def_id(item.hir_id); + let item_span = self.tcx.hir().span(item.hir_id); let self_ty = self.tcx.type_of(def_id); let lang_items = self.tcx.lang_items(); match self_ty.kind { @@ -69,7 +70,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "bool", "bool", - item.span, + item_span, ); } ty::Char => { @@ -79,7 +80,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "char", "char", - item.span, + item_span, ); } ty::Str => { @@ -89,7 +90,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { lang_items.str_alloc_impl(), "str", "str", - item.span, + item_span, ); } ty::Slice(slice_item) if slice_item == self.tcx.types.u8 => { @@ -99,7 +100,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { lang_items.slice_u8_alloc_impl(), "slice_u8", "[u8]", - item.span, + item_span, ); } ty::Slice(_) => { @@ -109,7 +110,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { lang_items.slice_alloc_impl(), "slice", "[T]", - item.span, + item_span, ); } ty::RawPtr(ty::TypeAndMut { ty: inner, mutbl: hir::Mutability::Not }) @@ -121,7 +122,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "const_slice_ptr", "*const [T]", - item.span, + item_span, ); } ty::RawPtr(ty::TypeAndMut { ty: inner, mutbl: hir::Mutability::Mut }) @@ -133,7 +134,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "mut_slice_ptr", "*mut [T]", - item.span, + item_span, ); } ty::RawPtr(ty::TypeAndMut { ty: _, mutbl: hir::Mutability::Not }) => { @@ -143,7 +144,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "const_ptr", "*const T", - item.span, + item_span, ); } ty::RawPtr(ty::TypeAndMut { ty: _, mutbl: hir::Mutability::Mut }) => { @@ -153,7 +154,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "mut_ptr", "*mut T", - item.span, + item_span, ); } ty::Int(ast::IntTy::I8) => { @@ -163,7 +164,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "i8", "i8", - item.span, + item_span, ); } ty::Int(ast::IntTy::I16) => { @@ -173,7 +174,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "i16", "i16", - item.span, + item_span, ); } ty::Int(ast::IntTy::I32) => { @@ -183,7 +184,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "i32", "i32", - item.span, + item_span, ); } ty::Int(ast::IntTy::I64) => { @@ -193,7 +194,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "i64", "i64", - item.span, + item_span, ); } ty::Int(ast::IntTy::I128) => { @@ -203,7 +204,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "i128", "i128", - item.span, + item_span, ); } ty::Int(ast::IntTy::Isize) => { @@ -213,7 +214,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "isize", "isize", - item.span, + item_span, ); } ty::Uint(ast::UintTy::U8) => { @@ -223,7 +224,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "u8", "u8", - item.span, + item_span, ); } ty::Uint(ast::UintTy::U16) => { @@ -233,7 +234,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "u16", "u16", - item.span, + item_span, ); } ty::Uint(ast::UintTy::U32) => { @@ -243,7 +244,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "u32", "u32", - item.span, + item_span, ); } ty::Uint(ast::UintTy::U64) => { @@ -253,7 +254,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "u64", "u64", - item.span, + item_span, ); } ty::Uint(ast::UintTy::U128) => { @@ -263,7 +264,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "u128", "u128", - item.span, + item_span, ); } ty::Uint(ast::UintTy::Usize) => { @@ -273,7 +274,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { None, "usize", "usize", - item.span, + item_span, ); } ty::Float(ast::FloatTy::F32) => { @@ -283,7 +284,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { lang_items.f32_runtime_impl(), "f32", "f32", - item.span, + item_span, ); } ty::Float(ast::FloatTy::F64) => { @@ -293,7 +294,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { lang_items.f64_runtime_impl(), "f64", "f64", - item.span, + item_span, ); } ty::Error(_) => {} @@ -329,14 +330,15 @@ impl InherentCollect<'tcx> { let vec = self.impls_map.inherent_impls.entry(def_id).or_default(); vec.push(impl_def_id.to_def_id()); } else { + let item_span = self.tcx.hir().span(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/src/librustc_typeck/coherence/orphan.rs b/src/librustc_typeck/coherence/orphan.rs index 71469770f2a33..3da6fee601d48 100644 --- a/src/librustc_typeck/coherence/orphan.rs +++ b/src/librustc_typeck/coherence/orphan.rs @@ -33,8 +33,9 @@ impl ItemLikeVisitor<'v> for OrphanChecker<'tcx> { ); let trait_ref = self.tcx.impl_trait_ref(def_id).unwrap(); let trait_def_id = trait_ref.def_id; + let item_span = self.tcx.hir().span(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, def_id.to_def_id()) { Ok(()) => {} Err(traits::OrphanCheckErr::NonLocalInputType(tys)) => { @@ -85,7 +86,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/src/librustc_typeck/coherence/unsafety.rs b/src/librustc_typeck/coherence/unsafety.rs index b281092ea631d..9ffc4881bc13f 100644 --- a/src/librustc_typeck/coherence/unsafety.rs +++ b/src/librustc_typeck/coherence/unsafety.rs @@ -25,6 +25,7 @@ impl UnsafetyChecker<'tcx> { polarity: hir::ImplPolarity, ) { let local_did = self.tcx.hir().local_def_id(item.hir_id); + let item_span = self.tcx.hir().span(item.hir_id); if let Some(trait_ref) = self.tcx.impl_trait_ref(local_did) { let trait_def = self.tcx.trait_def(trait_ref.def_id); let unsafe_attr = impl_generics.and_then(|generics| { @@ -34,7 +35,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() @@ -45,7 +46,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() @@ -61,7 +62,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 @@ -71,7 +72,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/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 054165f2b0977..c9d6ca73f6ae2 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -149,12 +149,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), )); } @@ -360,7 +362,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![ @@ -526,8 +529,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(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 } @@ -657,14 +661,16 @@ fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) { tcx.ensure().predicates_of(def_id); } hir::ItemKind::Trait(..) => { + let it_span = tcx.hir().span(it.hir_id); tcx.ensure().generics_of(def_id); tcx.ensure().trait_def(def_id); - tcx.at(it.span).super_predicates_of(def_id); + tcx.at(it_span).super_predicates_of(def_id); tcx.ensure().predicates_of(def_id); } hir::ItemKind::TraitAlias(..) => { + let it_span = tcx.hir().span(it.hir_id); tcx.ensure().generics_of(def_id); - tcx.at(it.span).super_predicates_of(def_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, _) => { @@ -774,11 +780,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 @@ -821,20 +825,15 @@ 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 { - struct_span_err!( - tcx.sess, - f.span, - E0124, - "field `{}` is already declared", - f.ident - ) - .span_label(f.span, "field already declared") - .span_label(prev_span, format!("`{}` first declared here", f.ident)) - .emit(); + struct_span_err!(tcx.sess, span, E0124, "field `{}` is already declared", f.ident) + .span_label(span, "field already declared") + .span_label(prev_span, format!("`{}` first declared here", f.ident)) + .emit(); } 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 { @@ -963,15 +962,16 @@ fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredi 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!(tcx.hir().span(item.hir_id), "super_predicates invoked on non-trait"), }; let icx = ItemCtxt::new(tcx, trait_def_id); // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`. let self_param_ty = tcx.types.self_param; + let item_span = tcx.hir().span(item.hir_id); let superbounds1 = - 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); @@ -1006,18 +1006,19 @@ fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredi fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef { let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()); let item = tcx.hir().expect_item(hir_id); + let item_span = tcx.hir().span(item.hir_id); 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"), + _ => 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 { 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", ) @@ -1113,7 +1114,8 @@ fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option, def_id: DefId) -> ty::Generics { if let GenericParamKind::Type { ref default, synthetic, .. } = param.kind { 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 \ @@ -1566,7 +1569,8 @@ fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity { } hir::ItemKind::Impl { polarity: hir::ImplPolarity::Positive, of_trait: None, .. } => { if is_rustc_reservation { - tcx.sess.span_err(item.span, "reservation impls can't be inherent"); + let item_span = tcx.hir().span(item.hir_id); + tcx.sess.span_err(item_span, "reservation impls can't be inherent"); } ty::ImplPolarity::Positive } @@ -1704,7 +1708,7 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat let ast_generics = match node { Node::TraitItem(item) => { if let hir::TraitItemKind::Type(bounds, _) = item.kind { - is_trait_associated_type = Some((bounds, item.span)); + is_trait_associated_type = Some((bounds, item.hir_id)); } &item.generics } @@ -1843,7 +1847,8 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat 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)); } } @@ -1935,11 +1940,11 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat if tcx.features().generic_associated_types { // New behavior: bounds declared on associate type are predicates of that // associated type. Not the default because it needs more testing. - if let Some((bounds, span)) = is_trait_associated_type { + if let Some((bounds, hir_id)) = is_trait_associated_type { let projection_ty = tcx.mk_projection(def_id, InternalSubsts::identity_for_item(tcx, def_id)); - predicates.extend(associated_item_bounds(tcx, def_id, bounds, projection_ty, span)) + predicates.extend(associated_item_bounds(tcx, def_id, bounds, projection_ty, hir_id)) } } else if let Some((self_trait_ref, trait_items)) = is_trait { // Current behavior: bounds declared on associate type are predicates @@ -1992,7 +1997,8 @@ fn trait_associated_item_predicates( // For GATs the substs provided to the mk_projection call below are // wrong. We should emit a feature gate error if we get here so skip // this type. - tcx.sess.delay_span_bug(trait_item.span, "gats used without feature gate"); + tcx.sess + .delay_span_bug(tcx.hir().span(trait_item.hir_id), "gats used without feature gate"); return Vec::new(); } @@ -2001,7 +2007,7 @@ fn trait_associated_item_predicates( self_trait_ref.substs, ); - associated_item_bounds(tcx, def_id, bounds, assoc_ty, trait_item.span) + associated_item_bounds(tcx, def_id, bounds, assoc_ty, trait_item.hir_id) } fn associated_item_bounds( @@ -2009,14 +2015,14 @@ fn associated_item_bounds( def_id: DefId, bounds: &'tcx [hir::GenericBound<'tcx>], projection_ty: Ty<'tcx>, - span: Span, + hir_id: hir::HirId, ) -> Vec<(ty::Predicate<'tcx>, Span)> { let bounds = AstConv::compute_bounds( &ItemCtxt::new(tcx, def_id), projection_ty, bounds, SizedByDefault::Yes, - span, + tcx.hir().span(hir_id), ); let predicates = bounds.predicates(tcx, projection_ty); diff --git a/src/librustc_typeck/collect/type_of.rs b/src/librustc_typeck/collect/type_of.rs index cf5f2ec69d8d8..b5dfaba387ca0 100644 --- a/src/librustc_typeck/collect/type_of.rs +++ b/src/librustc_typeck/collect/type_of.rs @@ -48,7 +48,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(item.hir_id); + span_bug!(item_span, "associated type missing default"); } }, @@ -66,7 +67,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() { - report_assoc_ty_on_inherent_impl(tcx, item.span); + let item_span = tcx.hir().span(item.hir_id); + report_assoc_ty_on_inherent_impl(tcx, item_span); } icx.to_ty(ty) @@ -148,8 +150,9 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { | ItemKind::GlobalAsm(..) | ItemKind::ExternCrate(..) | ItemKind::Use(..) => { + let item_span = tcx.hir().span(item.hir_id); span_bug!( - item.span, + item_span, "compute_type_of_item: unexpected item type: {:?}", item.kind ); @@ -322,7 +325,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { .emit(); }; } - if traits::search_for_structural_match_violation(param.hir_id, param.span, tcx, ty) + let param_span = tcx.hir().span(param.hir_id); + 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 diff --git a/src/librustc_typeck/expr_use_visitor.rs b/src/librustc_typeck/expr_use_visitor.rs index b72fae96e4ca0..a43a2e7a8b11d 100644 --- a/src/librustc_typeck/expr_use_visitor.rs +++ b/src/librustc_typeck/expr_use_visitor.rs @@ -101,7 +101,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); } @@ -505,7 +506,8 @@ 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,); - if let Some(bm) = mc.tables.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) { + let pat_span = tcx.hir().span(pat.hir_id); + if let Some(bm) = mc.tables.extract_binding_mode(tcx.sess, pat.hir_id, pat_span) { debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm); // pat_ty: the type of the binding being produced. @@ -515,7 +517,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); } diff --git a/src/librustc_typeck/impl_wf_check.rs b/src/librustc_typeck/impl_wf_check.rs index 37d383db68ab6..a3b3a00cdc8bb 100644 --- a/src/librustc_typeck/impl_wf_check.rs +++ b/src/librustc_typeck/impl_wf_check.rs @@ -85,7 +85,8 @@ impl ItemLikeVisitor<'tcx> for ImplWfCheck<'tcx> { enforce_impl_params_are_constrained(self.tcx, impl_def_id, items); enforce_impl_items_are_distinct(self.tcx, items); if self.min_specialization { - check_min_specialization(self.tcx, impl_def_id.to_def_id(), item.span); + let item_span = self.tcx.hir().span(item.hir_id); + check_min_specialization(self.tcx, impl_def_id.to_def_id(), item_span); } } } @@ -226,6 +227,7 @@ fn enforce_impl_items_are_distinct(tcx: TyCtxt<'_>, impl_item_refs: &[hir::ImplI let mut seen_value_items = FxHashMap::default(); for impl_item_ref in impl_item_refs { let impl_item = tcx.hir().impl_item(impl_item_ref.id); + let impl_item_span = tcx.hir().span(impl_item.hir_id); let seen_items = match impl_item.kind { hir::ImplItemKind::TyAlias(_) => &mut seen_type_items, _ => &mut seen_value_items, @@ -234,7 +236,7 @@ fn enforce_impl_items_are_distinct(tcx: TyCtxt<'_>, impl_item_refs: &[hir::ImplI Occupied(entry) => { let mut err = struct_span_err!( tcx.sess, - impl_item.span, + impl_item_span, E0201, "duplicate definitions with name `{}`:", impl_item.ident @@ -243,11 +245,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/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index 8d8a1b4d96761..6ec7eb33f62aa 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -183,7 +183,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 span = tcx.hir().span(it.hir_id); + let span = tcx.sess.source_map().guess_head_span(span); struct_span_err!( tcx.sess, span, @@ -263,7 +264,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 span = tcx.hir().span(it.hir_id); + let span = tcx.sess.source_map().guess_head_span(span); struct_span_err!( tcx.sess, span, diff --git a/src/librustc_typeck/mem_categorization.rs b/src/librustc_typeck/mem_categorization.rs index d619d37be2d7b..9c21902926d7f 100644 --- a/src/librustc_typeck/mem_categorization.rs +++ b/src/librustc_typeck/mem_categorization.rs @@ -142,25 +142,18 @@ impl<'tcx> Place<'tcx> { 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)] diff --git a/src/librustc_typeck/outlives/test.rs b/src/librustc_typeck/outlives/test.rs index abe9319d71c59..86a6eb9b293db 100644 --- a/src/librustc_typeck/outlives/test.rs +++ b/src/librustc_typeck/outlives/test.rs @@ -20,7 +20,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(item.hir_id); + struct_span_err!(self.tcx.sess, item_span, E0640, "{:?}", inferred_outlives_of).emit(); } } diff --git a/src/librustc_typeck/variance/test.rs b/src/librustc_typeck/variance/test.rs index 1aab89310c6e8..dbf0a79dcc830 100644 --- a/src/librustc_typeck/variance/test.rs +++ b/src/librustc_typeck/variance/test.rs @@ -20,7 +20,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(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 73fe87b05d477..4f55506d3293c 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1114,7 +1114,7 @@ impl Clean for hir::TraitItem<'_> { Item { name: Some(self.ident.name.clean(cx)), attrs: self.attrs.clean(cx), - source: self.span.clean(cx), + source: cx.tcx.hir().span(self.hir_id).clean(cx), def_id: local_did.to_def_id(), visibility: Visibility::Inherited, stability: get_stability(cx, local_did.to_def_id()), @@ -1142,7 +1142,7 @@ impl Clean for hir::ImplItem<'_> { let local_did = cx.tcx.hir().local_def_id(self.hir_id); Item { name: Some(self.ident.name.clean(cx)), - source: self.span.clean(cx), + source: cx.tcx.hir().span(self.hir_id).clean(cx), attrs: self.attrs.clean(cx), def_id: local_did.to_def_id(), visibility: self.vis.clean(cx), @@ -1736,11 +1736,12 @@ impl<'tcx> Clean for ty::Const<'tcx> { impl Clean for hir::StructField<'_> { fn clean(&self, cx: &DocContext<'_>) -> Item { let local_did = cx.tcx.hir().local_def_id(self.hir_id); + let span = cx.tcx.hir().span(self.hir_id); Item { name: Some(self.ident.name).clean(cx), attrs: self.attrs.clean(cx), - source: self.span.clean(cx), + source: span.clean(cx), visibility: self.vis.clean(cx), stability: get_stability(cx, local_did.to_def_id()), deprecation: get_deprecation(cx, local_did.to_def_id()), diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 21aa0ded5a4b2..81deaf9bb3618 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -137,7 +137,7 @@ pub fn run(options: Options) -> Result<(), String> { "".to_string(), &krate.item.attrs, CRATE_HIR_ID, - krate.item.span, + tcx.hir().span(CRATE_HIR_ID), |this| { intravisit::walk_crate(this, krate); }, @@ -980,25 +980,29 @@ impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> item.ident.to_string() }; - self.visit_testable(name, &item.attrs, item.hir_id, item.span, |this| { + let item_span = self.map.span(item.hir_id); + self.visit_testable(name, &item.attrs, 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.attrs, item.hir_id, item.span, |this| { + let item_span = self.map.span(item.hir_id); + self.visit_testable(item.ident.to_string(), &item.attrs, 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.attrs, item.hir_id, item.span, |this| { + let item_span = self.map.span(item.hir_id); + self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item_span, |this| { intravisit::walk_impl_item(this, item); }); } fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) { - self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| { + let item_span = self.map.span(item.hir_id); + self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item_span, |this| { intravisit::walk_foreign_item(this, item); }); } @@ -1009,15 +1013,21 @@ impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> g: &'hir hir::Generics, item_id: hir::HirId, ) { - self.visit_testable(v.ident.to_string(), &v.attrs, v.id, v.span, |this| { + self.visit_testable(v.ident.to_string(), &v.attrs, v.id, self.map.span(v.id), |this| { intravisit::walk_variant(this, v, g, item_id); }); } fn visit_struct_field(&mut self, f: &'hir hir::StructField) { - self.visit_testable(f.ident.to_string(), &f.attrs, f.hir_id, f.span, |this| { - intravisit::walk_struct_field(this, f); - }); + self.visit_testable( + f.ident.to_string(), + &f.attrs, + f.hir_id, + self.map.span(f.hir_id), + |this| { + intravisit::walk_struct_field(this, f); + }, + ); } fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) { @@ -1025,7 +1035,7 @@ impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> macro_def.ident.to_string(), ¯o_def.attrs, macro_def.hir_id, - macro_def.span, + self.map.span(macro_def.hir_id), |_| (), ); } diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index d2a950027cf87..fd8959c707db7 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -64,7 +64,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { pub fn visit(mut self, krate: &'tcx hir::Crate) -> Module<'tcx> { let mut module = self.visit_mod_contents( - krate.item.span, + self.cx.tcx.hir().span(hir::CRATE_HIR_ID), krate.item.attrs, &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public }, hir::CRATE_HIR_ID, @@ -99,7 +99,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { attrs: &item.attrs, generics, fields: sd.fields(), - whence: item.span, + whence: self.cx.tcx.hir().span(item.hir_id), } } @@ -120,7 +120,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { attrs: &item.attrs, generics, fields: sd.fields(), - whence: item.span, + whence: self.cx.tcx.hir().span(item.hir_id), } } @@ -142,14 +142,14 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { id: v.id, attrs: &v.attrs, def: &v.data, - whence: v.span, + whence: self.cx.tcx.hir().span(v.id), }) .collect(), vis: &it.vis, generics, attrs: &it.attrs, id: it.hir_id, - whence: it.span, + whence: self.cx.tcx.hir().span(it.hir_id), } } @@ -208,7 +208,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { kind, helpers, attrs: &item.attrs, - whence: item.span, + whence: self.cx.tcx.hir().span(item.hir_id), }); } None => { @@ -218,7 +218,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { attrs: &item.attrs, decl, name, - whence: item.span, + whence: self.cx.tcx.hir().span(item.hir_id), generics, header, body, @@ -401,7 +401,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { path: orig_name.map(|x| x.to_string()), vis: &item.vis, attrs: &item.attrs, - whence: item.span, + whence: self.cx.tcx.hir().span(item.hir_id), }) } hir::ItemKind::Use(_, hir::UseKind::ListStem) => {} @@ -443,12 +443,12 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { attrs: &item.attrs, path, glob: is_glob, - whence: item.span, + whence: self.cx.tcx.hir().span(item.hir_id), }); } hir::ItemKind::Mod(ref m) => { om.mods.push(self.visit_mod_contents( - item.span, + self.cx.tcx.hir().span(item.hir_id), &item.attrs, &item.vis, item.hir_id, @@ -475,7 +475,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { name: ident.name, id: item.hir_id, attrs: &item.attrs, - whence: item.span, + whence: self.cx.tcx.hir().span(item.hir_id), vis: &item.vis, }; om.typedefs.push(t); @@ -486,7 +486,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { name: ident.name, id: item.hir_id, attrs: &item.attrs, - whence: item.span, + whence: self.cx.tcx.hir().span(item.hir_id), vis: &item.vis, }; om.opaque_tys.push(t); @@ -499,7 +499,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { id: item.hir_id, name: ident.name, attrs: &item.attrs, - whence: item.span, + whence: self.cx.tcx.hir().span(item.hir_id), vis: &item.vis, }; om.statics.push(s); @@ -514,7 +514,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { id: item.hir_id, name: ident.name, attrs: &item.attrs, - whence: item.span, + whence: self.cx.tcx.hir().span(item.hir_id), vis: &item.vis, }; om.constants.push(s); @@ -531,7 +531,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { bounds, id: item.hir_id, attrs: &item.attrs, - whence: item.span, + whence: self.cx.tcx.hir().span(item.hir_id), vis: &item.vis, }; om.traits.push(t); @@ -543,7 +543,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { bounds, id: item.hir_id, attrs: &item.attrs, - whence: item.span, + whence: self.cx.tcx.hir().span(item.hir_id), vis: &item.vis, }; om.trait_aliases.push(t); @@ -576,7 +576,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { items, attrs: &item.attrs, id: item.hir_id, - whence: item.span, + whence: self.cx.tcx.hir().span(item.hir_id), vis: &item.vis, }; om.impls.push(i); @@ -602,7 +602,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { kind: &item.kind, vis: &item.vis, attrs: &item.attrs, - whence: item.span, + whence: self.cx.tcx.hir().span(item.hir_id), }); } @@ -618,7 +618,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { def_id: self.cx.tcx.hir().local_def_id(def.hir_id).to_def_id(), attrs: &def.attrs, name: renamed.unwrap_or(def.ident.name), - whence: def.span, + whence: self.cx.tcx.hir().span(def.hir_id), matchers, imported_from: None, } diff --git a/src/test/ui-fulldeps/auxiliary/issue-40001-plugin.rs b/src/test/ui-fulldeps/auxiliary/issue-40001-plugin.rs index 1b6a38acb1c30..36b7195026372 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<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingWhitelistedAttrPass { _: 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<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingWhitelistedAttrPass { let whitelisted = |attr| pprust::attribute_to_string(attr).contains("whitelisted_attr"); if !item.attrs.iter().any(whitelisted) { cx.lint(MISSING_WHITELISTED_ATTR, |lint| { + let span = cx.tcx.hir().span(id); lint.build("Missing 'whitelisted_attr' attribute").set_span(span).emit() }); } diff --git a/src/test/ui-fulldeps/auxiliary/lint-for-crate-rpass.rs b/src/test/ui-fulldeps/auxiliary/lint-for-crate-rpass.rs index f8cb1640cb4c1..71bc540501b2e 100644 --- a/src/test/ui-fulldeps/auxiliary/lint-for-crate-rpass.rs +++ b/src/test/ui-fulldeps/auxiliary/lint-for-crate-rpass.rs @@ -31,8 +31,9 @@ macro_rules! fake_lint_pass { $( if !attr::contains_name(&krate.item.attrs, $attr) { cx.lint(CRATE_NOT_OKAY, |lint| { + let span = cx.tcx.hir().span(rustc_hir::CRATE_HIR_ID); let msg = format!("crate is not marked with #![{}]", $attr); - lint.build(&msg).set_span(krate.item.span).emit() + lint.build(&msg).set_span(span).emit() }); } )* diff --git a/src/test/ui-fulldeps/auxiliary/lint-for-crate.rs b/src/test/ui-fulldeps/auxiliary/lint-for-crate.rs index 6978d02c09d14..b00a090556343 100644 --- a/src/test/ui-fulldeps/auxiliary/lint-for-crate.rs +++ b/src/test/ui-fulldeps/auxiliary/lint-for-crate.rs @@ -29,8 +29,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass { fn check_crate(&mut self, cx: &LateContext, krate: &rustc_hir::Crate) { if !attr::contains_name(&krate.item.attrs, Symbol::intern("crate_okay")) { cx.lint(CRATE_NOT_OKAY, |lint| { + let span = cx.tcx.hir().span(rustc_hir::CRATE_HIR_ID); lint.build("crate is not marked with #![crate_okay]") - .set_span(krate.item.span) + .set_span(span) .emit() }); } diff --git a/src/test/ui-fulldeps/auxiliary/lint-group-plugin-test.rs b/src/test/ui-fulldeps/auxiliary/lint-group-plugin-test.rs index 5a8eaa63db2f8..600e7eeba7a28 100644 --- a/src/test/ui-fulldeps/auxiliary/lint-group-plugin-test.rs +++ b/src/test/ui-fulldeps/auxiliary/lint-group-plugin-test.rs @@ -22,12 +22,13 @@ declare_lint_pass!(Pass => [TEST_LINT, PLEASE_LINT]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass { fn check_item(&mut self, cx: &LateContext, it: &rustc_hir::Item) { + let it_span = cx.tcx.hir().span(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() }), _ => {} } diff --git a/src/tools/clippy/clippy_lints/src/attrs.rs b/src/tools/clippy/clippy_lints/src/attrs.rs index 41f125d48398f..57f1bc7529c9b 100644 --- a/src/tools/clippy/clippy_lints/src/attrs.rs +++ b/src/tools/clippy/clippy_lints/src/attrs.rs @@ -280,7 +280,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Attributes { fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) { if is_relevant_item(cx, item) { - check_attrs(cx, item.span, item.ident.name, &item.attrs) + check_attrs(cx, cx.tcx.hir().span(item.hir_id), item.ident.name, &item.attrs) } match item.kind { ItemKind::ExternCrate(..) | ItemKind::Use(..) => { @@ -352,13 +352,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Attributes { fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem<'_>) { if is_relevant_impl(cx, item) { - check_attrs(cx, item.span, item.ident.name, &item.attrs) + check_attrs(cx, cx.tcx.hir().span(item.hir_id), item.ident.name, &item.attrs) } } fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem<'_>) { if is_relevant_trait(cx, item) { - check_attrs(cx, item.span, item.ident.name, &item.attrs) + check_attrs(cx, cx.tcx.hir().span(item.hir_id), item.ident.name, &item.attrs) } } } 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 8fa9b05ca3297..9340123f71066 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 @@ -107,7 +107,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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; } @@ -123,7 +123,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BlocksInIfConditions { "let res = {}; if res", snippet_block_with_applicability( cx, - block.span, + cx.tcx.hir().span(block.hir_id), "..", Some(expr.span), &mut applicability diff --git a/src/tools/clippy/clippy_lints/src/booleans.rs b/src/tools/clippy/clippy_lints/src/booleans.rs index f92c564543b89..62ca571f9acd8 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; declare_clippy_lint! { /// **What it does:** Checks for boolean expressions that can be written more @@ -62,7 +61,6 @@ impl<'a, 'tcx> LateLintPass<'a, '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 3ba72e84fa827..4c362f6d84ac6 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<'a, 'tcx> LateLintPass<'a, '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/copies.rs b/src/tools/clippy/clippy_lints/src/copies.rs index b6d50bdfa1466..779b54660d1d1 100644 --- a/src/tools/clippy/clippy_lints/src/copies.rs +++ b/src/tools/clippy/clippy_lints/src/copies.rs @@ -181,9 +181,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", ); } @@ -285,8 +285,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 _ @@ -300,7 +300,7 @@ fn lint_match_arms<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &Expr<'_>) { ), ); } else { - diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs)); + diag.span_help(cx.tcx.hir().span(i.pat.hir_id), &format!("consider refactoring into `{} | {}`", lhs, rhs)); } }, ); diff --git a/src/tools/clippy/clippy_lints/src/copy_iterator.rs b/src/tools/clippy/clippy_lints/src/copy_iterator.rs index d79aa2ef0209e..a3ae85a452210 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<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyIterator { span_lint_and_note( cx, COPY_ITERATOR, - item.span, + cx.tcx.hir().span(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 3cbb8fa72f74f..59da2c77308b7 100644 --- a/src/tools/clippy/clippy_lints/src/derive.rs +++ b/src/tools/clippy/clippy_lints/src/derive.rs @@ -115,7 +115,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Derive { let ty = cx.tcx.type_of(cx.tcx.hir().local_def_id(item.hir_id)); let is_automatically_derived = is_automatically_derived(&*item.attrs); - check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived); + check_hash_peq(cx, cx.tcx.hir().span(item.hir_id), trait_ref, ty, is_automatically_derived); if is_automatically_derived { check_unsafe_derive_deserialize(cx, item, trait_ref, ty); @@ -210,12 +210,13 @@ fn check_copy_clone<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, item: &Item<'_>, trait _ => (), } + let item_span = cx.tcx.hir().span(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`", ); } @@ -251,7 +252,7 @@ fn check_unsafe_derive_deserialize<'a, 'tcx>( span_lint_and_help( cx, UNSAFE_DERIVE_DESERIALIZE, - item.span, + cx.tcx.hir().span(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" @@ -268,7 +269,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; } @@ -281,7 +282,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/doc.rs b/src/tools/clippy/clippy_lints/src/doc.rs index 8d1e91f9adbd6..e530e4d12b176 100644 --- a/src/tools/clippy/clippy_lints/src/doc.rs +++ b/src/tools/clippy/clippy_lints/src/doc.rs @@ -155,10 +155,11 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DocMarkdown { let headers = check_attrs(cx, &self.valid_idents, &item.attrs); match item.kind { hir::ItemKind::Fn(ref sig, _, body_id) => { + let item_span = cx.tcx.hir().span(item.hir_id); if !(is_entrypoint_fn(cx, cx.tcx.hir().local_def_id(item.hir_id).to_def_id()) - || in_external_macro(cx.tcx.sess, item.span)) + || in_external_macro(cx.tcx.sess, item_span)) { - lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id)); + lint_for_missing_headers(cx, item.hir_id, item_span, sig, headers, Some(body_id)); } }, hir::ItemKind::Impl { @@ -180,19 +181,21 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DocMarkdown { fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem<'_>) { let headers = check_attrs(cx, &self.valid_idents, &item.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); + let item_span = cx.tcx.hir().span(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); } } } fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem<'_>) { let headers = check_attrs(cx, &self.valid_idents, &item.attrs); - if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) { + let item_span = cx.tcx.hir().span(item.hir_id); + 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 { - lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id)); + lint_for_missing_headers(cx, item.hir_id, 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 3bfef6f4bed12..ea1969ed9f683 100644 --- a/src/tools/clippy/clippy_lints/src/empty_enum.rs +++ b/src/tools/clippy/clippy_lints/src/empty_enum.rs @@ -48,7 +48,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EmptyEnum { span_lint_and_help( cx, EMPTY_ENUM, - item.span, + cx.tcx.hir().span(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/enum_clike.rs b/src/tools/clippy/clippy_lints/src/enum_clike.rs index 12b62f5cf9789..92e5d23c2823e 100644 --- a/src/tools/clippy/clippy_lints/src/enum_clike.rs +++ b/src/tools/clippy/clippy_lints/src/enum_clike.rs @@ -71,7 +71,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnportableVariant { span_lint( cx, ENUM_CLIKE_UNPORTABLE_VARIANT, - var.span, + cx.tcx.hir().span(var.id), "Clike enum variant discriminant is not portable to 32-bit targets", ); }; diff --git a/src/tools/clippy/clippy_lints/src/escape.rs b/src/tools/clippy/clippy_lints/src/escape.rs index 59af475af175e..91cb6c5bdbc44 100644 --- a/src/tools/clippy/clippy_lints/src/escape.rs +++ b/src/tools/clippy/clippy_lints/src/escape.rs @@ -4,7 +4,6 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, Ty}; use rustc_session::{declare_tool_lint, impl_lint_pass}; -use rustc_span::source_map::Span; use rustc_target::abi::LayoutOf; use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceWithHirId, PlaceBase}; @@ -63,7 +62,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxedLocal { _: intravisit::FnKind<'tcx>, _: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - _: Span, hir_id: HirId, ) { // If the method is an impl for a trait, don't warn. 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 92812816461c5..8b0013a565bbe 100644 --- a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs +++ b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs @@ -61,7 +61,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for FallibleImplFrom { if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(impl_def_id); if match_def_path(cx, impl_trait_ref.def_id, &FROM_TRAIT); then { - lint_impl_body(cx, item.span, impl_items); + lint_impl_body(cx, cx.tcx.hir().span(item.hir_id), impl_items); } } } diff --git a/src/tools/clippy/clippy_lints/src/functions.rs b/src/tools/clippy/clippy_lints/src/functions.rs index 991d129e8f0d6..1d9d3838ddf51 100644 --- a/src/tools/clippy/clippy_lints/src/functions.rs +++ b/src/tools/clippy/clippy_lints/src/functions.rs @@ -197,7 +197,6 @@ impl<'a, 'tcx> LateLintPass<'a, '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 { @@ -206,6 +205,8 @@ impl<'a, 'tcx> LateLintPass<'a, '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 @@ -233,9 +234,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions { fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) { let attr = must_use_attr(&item.attrs); if let hir::ItemKind::Fn(ref sig, ref _generics, ref body_id) = item.kind { + let item_span = cx.tcx.hir().span(item.hir_id); if let Some(attr) = attr { - let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); - check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr); + let fn_header_span = item_span.with_hi(sig.decl.output.span().hi()); + check_needless_must_use(cx, &sig.decl, item.hir_id, item_span, fn_header_span, attr); return; } if cx.access_levels.is_exported(item.hir_id) @@ -246,9 +248,9 @@ impl<'a, 'tcx> LateLintPass<'a, '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", ); } @@ -258,9 +260,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions { fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem<'_>) { if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind { let attr = must_use_attr(&item.attrs); + let item_span = cx.tcx.hir().span(item.hir_id); if let Some(attr) = attr { - let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); - check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr); + let fn_header_span = item_span.with_hi(sig.decl.output.span().hi()); + check_needless_must_use(cx, &sig.decl, item.hir_id, item_span, fn_header_span, attr); } else if cx.access_levels.is_exported(item.hir_id) && !is_proc_macro(&item.attrs) && trait_ref_of_method(cx, item.hir_id).is_none() @@ -269,9 +272,9 @@ impl<'a, 'tcx> LateLintPass<'a, '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 method could have a `#[must_use]` attribute", ); } @@ -280,15 +283,17 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions { fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem<'_>) { if let hir::TraitItemKind::Fn(ref sig, ref eid) = item.kind { + let item_span = cx.tcx.hir().span(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 attr = must_use_attr(&item.attrs); if let Some(attr) = attr { - let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); - check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr); + let fn_header_span = item_span.with_hi(sig.decl.output.span().hi()); + 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); @@ -299,9 +304,9 @@ impl<'a, 'tcx> LateLintPass<'a, '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", ); } @@ -498,7 +503,7 @@ fn is_mutable_pat(cx: &LateContext<'_, '_>, pat: &hir::Pat<'_>, tys: &mut FxHash is_mutable_ty( cx, &cx.tcx.typeck_tables_of(def_id.expect_local()).pat_ty(pat), - pat.span, + cx.tcx.hir().span(pat.hir_id), tys, ) } else { 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 17dd3cd5493e7..df0803007a2ad 100644 --- a/src/tools/clippy/clippy_lints/src/future_not_send.rs +++ b/src/tools/clippy/clippy_lints/src/future_not_send.rs @@ -5,7 +5,7 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{Opaque, PredicateKind::Trait, ToPolyTraitRef}; 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}; @@ -54,7 +54,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for FutureNotSend { kind: FnKind<'tcx>, decl: &'tcx FnDecl<'tcx>, _: &'tcx Body<'tcx>, - _: Span, hir_id: HirId, ) { if let FnKind::Closure(_) = kind { diff --git a/src/tools/clippy/clippy_lints/src/if_let_some_result.rs b/src/tools/clippy/clippy_lints/src/if_let_some_result.rs index 6a1fcdd1ce445..ef86a603ebf41 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<'a, 'tcx> LateLintPass<'a, 'tcx> for OkIfLet { then { let mut applicability = Applicability::MachineApplicable; - let some_expr_string = snippet_with_applicability(cx, y[0].span, "", &mut applicability); + let some_expr_string = snippet_with_applicability(cx, cx.tcx.hir().span(y[0].hir_id), "", &mut applicability); let trimmed_ok = snippet_with_applicability(cx, op.span.until(ok_span), "", &mut applicability); let sugg = format!( "if let Ok({}) = {}", diff --git a/src/tools/clippy/clippy_lints/src/implicit_return.rs b/src/tools/clippy/clippy_lints/src/implicit_return.rs index c4308fd26a302..7310a5b99d07b 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_return.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_return.rs @@ -129,8 +129,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitReturn { _: FnKind<'tcx>, _: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - span: Span, - _: HirId, + hir_id: HirId, ) { let def_id = cx.tcx.hir().body_owner_def_id(body.id()); @@ -140,6 +139,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitReturn { } let mir = cx.tcx.optimized_mir(def_id.to_def_id()); + let span = cx.tcx.hir().span(hir_id); // checking return type through MIR, HIR is not able to determine inferred closure return types // make sure it's not a macro diff --git a/src/tools/clippy/clippy_lints/src/inherent_impl.rs b/src/tools/clippy/clippy_lints/src/inherent_impl.rs index 7e2975ac2ae90..ff087d47df5fd 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<'a, 'tcx> LateLintPass<'a, 'tcx> for MultipleInherentImpl { - fn check_item(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) { + fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) { if let ItemKind::Impl { ref generics, of_trait: None, @@ -58,8 +58,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MultipleInherentImpl { // Remember for each inherent implementation encoutered 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.hir_id.owner.to_def_id(), item.span); + let item_span = cx.tcx.hir().span(item.hir_id); + if !in_macro(item_span) && generics.params.is_empty() { + self.impls.insert(item.hir_id.owner.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 289628a2752af..15352edfc593b 100644 --- a/src/tools/clippy/clippy_lints/src/inherent_to_string.rs +++ b/src/tools/clippy/clippy_lints/src/inherent_to_string.rs @@ -94,7 +94,7 @@ declare_lint_pass!(InherentToString => [INHERENT_TO_STRING, INHERENT_TO_STRING_S impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InherentToString { fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, impl_item: &'tcx ImplItem<'_>) { - if impl_item.span.from_expansion() { + if cx.tcx.hir().span(impl_item.hir_id).from_expansion() { return; } @@ -132,7 +132,7 @@ fn show_lint(cx: &LateContext<'_, '_>, item: &ImplItem<'_>) { span_lint_and_help( cx, INHERENT_TO_STRING_SHADOW_DISPLAY, - item.span, + cx.tcx.hir().span(item.hir_id), &format!( "type `{}` implements inherent method `to_string(&self) -> String` which shadows the implementation of `Display`", self_type.to_string() @@ -144,7 +144,7 @@ fn show_lint(cx: &LateContext<'_, '_>, item: &ImplItem<'_>) { span_lint_and_help( cx, INHERENT_TO_STRING, - item.span, + cx.tcx.hir().span(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 c9e12fc535ec0..4ae6d38399d2b 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<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeConstArrays { fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) { + let item_span = cx.tcx.hir().span(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; @@ -63,12 +64,12 @@ impl<'a, 'tcx> LateLintPass<'a, '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 5bc3234e3252f..41f678787618f 100644 --- a/src/tools/clippy/clippy_lints/src/large_enum_variant.rs +++ b/src/tools/clippy/clippy_lints/src/large_enum_variant.rs @@ -96,15 +96,15 @@ impl<'a, 'tcx> LateLintPass<'a, '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 { @@ -124,7 +124,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs index 13e85fda8ffeb..990c479874a02 100644 --- a/src/tools/clippy/clippy_lints/src/len_zero.rs +++ b/src/tools/clippy/clippy_lints/src/len_zero.rs @@ -72,7 +72,7 @@ declare_lint_pass!(LenZero => [LEN_ZERO, LEN_WITHOUT_IS_EMPTY]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LenZero { fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) { - if item.span.from_expansion() { + if cx.tcx.hir().span(item.hir_id).from_expansion() { return; } @@ -159,7 +159,7 @@ fn check_trait_items(cx: &LateContext<'_, '_>, visited_trait: &Item<'_>, trait_i span_lint( cx, LEN_WITHOUT_IS_EMPTY, - visited_trait.span, + cx.tcx.hir().span(visited_trait.hir_id), &format!( "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method", visited_trait.ident.name @@ -200,7 +200,7 @@ fn check_impl_items(cx: &LateContext<'_, '_>, item: &Item<'_>, impl_items: &[Imp span_lint( cx, LEN_WITHOUT_IS_EMPTY, - item.span, + cx.tcx.hir().span(item.hir_id), &format!( "item `{}` has a public `len` method but {} `is_empty` method", ty, is_empty diff --git a/src/tools/clippy/clippy_lints/src/let_and_return.rs b/src/tools/clippy/clippy_lints/src/let_and_return.rs index 6d3fb317bcfc5..e1c03ba988f24 100644 --- a/src/tools/clippy/clippy_lints/src/let_and_return.rs +++ b/src/tools/clippy/clippy_lints/src/let_and_return.rs @@ -56,8 +56,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetReturn { 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, @@ -65,13 +66,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetReturn { 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(snippet) = snippet_opt(cx, initexpr.span) { 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/let_if_seq.rs b/src/tools/clippy/clippy_lints/src/let_if_seq.rs index d7bf8a1476817..e7a5a2e0846e4 100644 --- a/src/tools/clippy/clippy_lints/src/let_if_seq.rs +++ b/src/tools/clippy/clippy_lints/src/let_if_seq.rs @@ -71,7 +71,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetIfSeq { if let Some(value) = check_assign(cx, canonical_id, &*then); if !used_in_expr(cx, canonical_id, 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.tables.node_type(canonical_id).is_freeze( cx.tcx, diff --git a/src/tools/clippy/clippy_lints/src/let_underscore.rs b/src/tools/clippy/clippy_lints/src/let_underscore.rs index 710dec8d33fc9..1bb04a42dd0c4 100644 --- a/src/tools/clippy/clippy_lints/src/let_underscore.rs +++ b/src/tools/clippy/clippy_lints/src/let_underscore.rs @@ -68,7 +68,8 @@ const SYNC_GUARD_PATHS: [&[&str]; 3] = [ impl<'a, 'tcx> LateLintPass<'a, '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; } @@ -88,7 +89,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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 \ @@ -98,7 +99,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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" @@ -107,7 +108,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnderscore { span_lint_and_help( cx, LET_UNDERSCORE_MUST_USE, - local.span, + local_span, "non-binding let on a result of a `#[must_use]` function", None, "consider explicitly using function result" diff --git a/src/tools/clippy/clippy_lints/src/lifetimes.rs b/src/tools/clippy/clippy_lints/src/lifetimes.rs index 318d0b69d57b7..8e1de19fefb8e 100644 --- a/src/tools/clippy/clippy_lints/src/lifetimes.rs +++ b/src/tools/clippy/clippy_lints/src/lifetimes.rs @@ -79,7 +79,7 @@ declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Lifetimes { fn check_item(&mut self, cx: &LateContext<'a, '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(item.hir_id), true); } } @@ -91,7 +91,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Lifetimes { &sig.decl, Some(id), &item.generics, - item.span, + cx.tcx.hir().span(item.hir_id), report_extra_lifetimes, ); } @@ -103,7 +103,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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(item.hir_id), true); } } } @@ -487,7 +487,7 @@ fn report_extra_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDe .params .iter() .filter_map(|par| match par.kind { - GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)), + GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, cx.tcx.hir().span(par.hir_id))), _ => None, }) .collect(); diff --git a/src/tools/clippy/clippy_lints/src/loops.rs b/src/tools/clippy/clippy_lints/src/loops.rs index 83093ec51bd90..81881c09303c9 100644 --- a/src/tools/clippy/clippy_lints/src/loops.rs +++ b/src/tools/clippy/clippy_lints/src/loops.rs @@ -510,7 +510,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Loops { "try", format!( "while let {} = {} {{ .. }}", - snippet_with_applicability(cx, arms[0].pat.span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(arms[0].pat.hir_id), "..", &mut applicability), snippet_with_applicability(cx, matchexpr.span, "..", &mut applicability), ), applicability, @@ -556,7 +556,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Loops { let loop_var = if pat_args.is_empty() { "_".to_string() } else { - snippet_with_applicability(cx, pat_args[0].span, "_", &mut applicability).into_owned() + snippet_with_applicability(cx, cx.tcx.hir().span(pat_args[0].hir_id), "_", &mut applicability).into_owned() }; span_lint_and_sugg( cx, @@ -1150,7 +1150,7 @@ fn check_for_loop_range<'a, '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), @@ -1178,7 +1178,7 @@ fn check_for_loop_range<'a, '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)], ); }, ); @@ -1314,7 +1314,7 @@ fn check_arg_type(cx: &LateContext<'_, '_>, pat: &Pat<'_>, arg: &Expr<'_>) { None, &format!( "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`", - snippet(cx, pat.span, "_"), + snippet(cx, cx.tcx.hir().span(pat.hir_id), "_"), snippet(cx, arg.span, "_") ), ); @@ -1331,7 +1331,7 @@ fn check_arg_type(cx: &LateContext<'_, '_>, pat: &Pat<'_>, arg: &Expr<'_>) { None, &format!( "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`", - snippet(cx, pat.span, "_"), + snippet(cx, cx.tcx.hir().span(pat.hir_id), "_"), snippet(cx, arg.span, "_") ), ); @@ -1390,7 +1390,7 @@ fn check_for_loop_explicit_counter<'a, '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, @@ -1444,15 +1444,15 @@ fn check_for_loop_over_map_kv<'a, '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.tables.expr_ty(arg).kind { ty::Ref(_, ty, mutbl) => match (&pat[0].kind, &pat[1].kind) { - (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", ty, mutbl), - (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", ty, Mutability::Not), + (key, _) if pat_is_wild(key, body) => (cx.tcx.hir().span(pat[1].hir_id), "value", ty, mutbl), + (_, value) if pat_is_wild(value, body) => (cx.tcx.hir().span(pat[0].hir_id), "key", ty, Mutability::Not), _ => return, }, _ => return, 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 03ab274d9ca9c..9363992e1e27a 100644 --- a/src/tools/clippy/clippy_lints/src/manual_async_fn.rs +++ b/src/tools/clippy/clippy_lints/src/manual_async_fn.rs @@ -9,7 +9,6 @@ use rustc_hir::{ }; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::Span; declare_clippy_lint! { /// **What it does:** It checks for manual implementations of `async` functions. @@ -45,8 +44,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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(); @@ -60,6 +58,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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( @@ -81,9 +80,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ManualAsyncFn { Applicability::MachineApplicable ); - let body_snip = snippet_block(cx, closure_body.value.span, "..", Some(block.span)); + let block_span = cx.tcx.hir().span(block.hir_id); + let body_snip = snippet_block(cx, closure_body.value.span, "..", Some(block_span)); diag.span_suggestion( - block.span, + block_span, "move the body of the async block to the enclosing function", body_snip.to_string(), Applicability::MachineApplicable diff --git a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs index 8f4b674c04f49..6a37c45808ffe 100644 --- a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs +++ b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs @@ -140,9 +140,9 @@ fn reduce_unit_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a hir::Expr<'_>) // If block only contains statements, // reduce `{ X; }` to `X` or `X;` match inner_stmt.kind { - hir::StmtKind::Local(ref local) => Some(local.span), + hir::StmtKind::Local(ref local) => Some(cx.tcx.hir().span(local.hir_id)), hir::StmtKind::Expr(ref e) => Some(e.span), - hir::StmtKind::Semi(..) => Some(inner_stmt.span), + hir::StmtKind::Semi(..) => Some(cx.tcx.hir().span(inner_stmt.hir_id)), hir::StmtKind::Item(..) => None, } }, @@ -214,6 +214,7 @@ fn lint_map_unit_fn(cx: &LateContext<'_, '_>, stmt: &hir::Stmt<'_>, expr: &hir:: }; 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!( @@ -225,7 +226,7 @@ fn lint_map_unit_fn(cx: &LateContext<'_, '_>, stmt: &hir::Stmt<'_>, expr: &hir:: ); 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); @@ -235,12 +236,12 @@ fn lint_map_unit_fn(cx: &LateContext<'_, '_>, stmt: &hir::Stmt<'_>, expr: &hir:: let suggestion = format!( "if let {0}({1}) = {2} {{ {3} }}", variant, - snippet(cx, binding.pat.span, "_"), + snippet(cx, cx.tcx.hir().span(binding.pat.hir_id), "_"), snippet(cx, var_arg.span, "_"), snippet(cx, reduced_expr_span, "_") ); diag.span_suggestion( - stmt.span, + stmt_span, "try this", suggestion, Applicability::MachineApplicable, // snippet @@ -249,10 +250,10 @@ fn lint_map_unit_fn(cx: &LateContext<'_, '_>, stmt: &hir::Stmt<'_>, expr: &hir:: let suggestion = format!( "if let {0}({1}) = {2} {{ ... }}", variant, - snippet(cx, binding.pat.span, "_"), + snippet(cx, cx.tcx.hir().span(binding.pat.hir_id), "_"), snippet(cx, var_arg.span, "_"), ); - diag.span_suggestion(stmt.span, "try this", suggestion, Applicability::HasPlaceholders); + diag.span_suggestion(stmt_span, "try this", suggestion, Applicability::HasPlaceholders); } }); } @@ -260,7 +261,7 @@ fn lint_map_unit_fn(cx: &LateContext<'_, '_>, stmt: &hir::Stmt<'_>, expr: &hir:: impl<'a, 'tcx> LateLintPass<'a, '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 6d7af45a47224..6075ee707e675 100644 --- a/src/tools/clippy/clippy_lints/src/matches.rs +++ b/src/tools/clippy/clippy_lints/src/matches.rs @@ -456,9 +456,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Matches { } fn check_local(&mut self, cx: &LateContext<'a, '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(); @@ -475,15 +476,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Matches { span_lint_and_sugg( cx, INFALLIBLE_DESTRUCTURING_MATCH, - local.span, + local_span, "you seem to be trying to use `match` to destructure a single infallible pattern. \ Consider using `let`", "try this", format!( "let {}({}) = {};", snippet_with_applicability(cx, variant_name.span, "..", &mut applicability), - snippet_with_applicability(cx, local.pat.span, "..", &mut applicability), - snippet_with_applicability(cx, target.span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(local.pat.hir_id), "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(target.hir_id), "..", &mut applicability), ), applicability, ); @@ -492,9 +493,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Matches { } fn check_pat(&mut self, cx: &LateContext<'a, '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(ref qpath, fields, true) = pat.kind; if let QPath::Resolved(_, ref path) = qpath; if let Some(def_id) = path.res.opt_def_id(); @@ -507,7 +509,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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", @@ -580,7 +582,7 @@ fn report_single_match_single_pattern( "try this", format!( "if let {} = {} {}{}", - snippet(cx, arms[0].pat.span, ".."), + snippet(cx, cx.tcx.hir().span(arms[0].pat.hir_id), ".."), snippet(cx, ex.span, ".."), expr_block(cx, &arms[0].body, None, "..", Some(expr.span)), els_str, @@ -736,12 +738,12 @@ fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) if_chain! { if matching_wild; if let ExprKind::Block(ref block, _) = arm.body.kind; - if is_panic_block(block); + if is_panic_block(cx, block); then { // `Err(_)` or `Err(_e)` arm with `panic!` found span_lint_and_note(cx, MATCH_WILD_ERR_ARM, - arm.pat.span, + cx.tcx.hir().span(arm.pat.hir_id), &format!("`Err({})` matches all errors", &ident_bind_name), None, "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable", @@ -768,9 +770,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); } } @@ -872,13 +874,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, } @@ -905,7 +908,7 @@ fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_> 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 } @@ -979,7 +982,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.", @@ -994,7 +997,7 @@ fn check_match_single_binding<'a>(cx: &LateContext<'_, 'a>, ex: &Expr<'a>, arms: return; } 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() @@ -1006,7 +1009,7 @@ fn check_match_single_binding<'a>(cx: &LateContext<'_, 'a>, ex: &Expr<'a>, arms: match match_body.kind { ExprKind::Block(block, _) => { // macro + expr_ty(body) == () - if block.span.from_expansion() && cx.tables.expr_ty(&match_body).is_unit() { + if cx.tcx.hir().span(block.hir_id).from_expansion() && cx.tables.expr_ty(&match_body).is_unit() { snippet_body.push(';'); } }, @@ -1024,13 +1027,13 @@ fn check_match_single_binding<'a>(cx: &LateContext<'_, 'a>, ex: &Expr<'a>, arms: // If this match is in a local (`let`) stmt let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) { ( - parent_let_node.span, + cx.tcx.hir().span(parent_let_node.hir_id), format!( "let {} = {};\n{}let {} = {};", snippet_with_applicability(cx, bind_names, "..", &mut applicability), snippet_with_applicability(cx, matched_vars, "..", &mut applicability), " ".repeat(indent_of(cx, expr.span).unwrap_or(0)), - snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability), + snippet_with_applicability(cx, cx.tcx.hir().span(parent_let_node.pat.hir_id), "..", &mut applicability), snippet_body ), ) @@ -1123,7 +1126,7 @@ fn all_ranges<'a, 'tcx>( RangeEnd::Excluded => Bound::Excluded(rhs), }; return Some(SpannedRange { - span: pat.span, + span: cx.tcx.hir().span(pat.hir_id), node: (lhs, rhs), }); } @@ -1131,7 +1134,7 @@ fn all_ranges<'a, 'tcx>( if let PatKind::Lit(ref value) = pat.kind { let value = constant(cx, cx.tables, value)?.0; return Some(SpannedRange { - span: pat.span, + span: cx.tcx.hir().span(pat.hir_id), node: (value.clone(), Bound::Included(value)), }); } diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index f25a9782813bb..a102da0b3bfe5 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -1472,7 +1472,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods { } fn check_impl_item(&mut self, cx: &LateContext<'a, '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(impl_item.hir_id)) { return; } let name = impl_item.ident.name.as_str(); @@ -1503,7 +1503,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods { out_type.matches(cx, &sig.decl.output) && self_kind.matches(cx, self_ty, first_arg_ty) && fn_header_equals(*fn_header, sig.header) { - span_lint(cx, SHOULD_IMPLEMENT_TRAIT, impl_item.span, &format!( + span_lint(cx, SHOULD_IMPLEMENT_TRAIT, cx.tcx.hir().span(impl_item.hir_id), &format!( "defining a method called `{}` on this type; consider implementing \ the `{}` trait or choosing a less ambiguous name", name, trait_name)); } @@ -1524,7 +1524,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods { span_lint( cx, lint, - first_arg.pat.span, + cx.tcx.hir().span(first_arg.pat.hir_id), &format!("methods called `{}` usually take {}; consider choosing a less ambiguous name", conv, &self_kinds @@ -1575,7 +1575,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods { span_lint( cx, NEW_RET_NO_SELF, - impl_item.span, + cx.tcx.hir().span(impl_item.hir_id), "methods called `new` usually return `Self`", ); } diff --git a/src/tools/clippy/clippy_lints/src/misc.rs b/src/tools/clippy/clippy_lints/src/misc.rs index a0947608e6077..ddb3569045e2b 100644 --- a/src/tools/clippy/clippy_lints/src/misc.rs +++ b/src/tools/clippy/clippy_lints/src/misc.rs @@ -267,7 +267,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MiscLints { k: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - _: Span, _: HirId, ) { if let FnKind::Closure(_) = k { @@ -279,7 +278,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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.", ); @@ -314,11 +313,11 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MiscLints { cx, TOPLEVEL_REF_ARG, init.hir_id, - local.pat.span, + cx.tcx.hir().span(local.pat.hir_id), "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead", |diag| { diag.span_suggestion( - stmt.span, + cx.tcx.hir().span(stmt.hir_id), "try", format!( "let {name}{tyopt} = {initref};", @@ -339,14 +338,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MiscLints { if binop.node == BinOpKind::And || binop.node == BinOpKind::Or; if let Some(sugg) = Sugg::hir_opt(cx, a); then { + let stmt_span = cx.tcx.hir().span(stmt.hir_id); span_lint_and_then(cx, SHORT_CIRCUIT_STATEMENT, - stmt.span, + stmt_span, "boolean short circuit operator in statement may be clearer using an explicit test", |diag| { let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg }; diag.span_suggestion( - stmt.span, + stmt_span, "replace it with", format!( "if {} {{ {}; }}", diff --git a/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs b/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs index 9cfc8d1913497..b307cf1cc8009 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 @@ -6,7 +6,6 @@ use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::lint::in_external_macro; use rustc_mir::transform::qualify_min_const_fn::is_min_const_fn; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::Span; use rustc_typeck::hir_ty_to_ty; declare_clippy_lint! { @@ -78,10 +77,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingConstForFn { kind: FnKind<'_>, _: &FnDecl<'_>, _: &Body<'_>, - span: Span, hir_id: HirId, ) { 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/missing_doc.rs b/src/tools/clippy/clippy_lints/src/missing_doc.rs index 0fd1e87f9e415..3de3b60fc068c 100644 --- a/src/tools/clippy/clippy_lints/src/missing_doc.rs +++ b/src/tools/clippy/clippy_lints/src/missing_doc.rs @@ -125,7 +125,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { } fn check_crate(&mut self, cx: &LateContext<'a, 'tcx>, krate: &'tcx hir::Crate<'_>) { - self.check_missing_docs_attrs(cx, &krate.item.attrs, krate.item.span, "crate"); + self.check_missing_docs_attrs(cx, &krate.item.attrs, cx.tcx.hir().span(hir::CRATE_HIR_ID), "crate"); } fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, it: &'tcx hir::Item<'_>) { @@ -158,7 +158,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { | hir::ItemKind::Use(..) => return, }; - self.check_missing_docs_attrs(cx, &it.attrs, it.span, desc); + self.check_missing_docs_attrs(cx, &it.attrs, cx.tcx.hir().span(it.hir_id), desc); } fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, trait_item: &'tcx hir::TraitItem<'_>) { @@ -168,7 +168,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { hir::TraitItemKind::Type(..) => "an associated type", }; - self.check_missing_docs_attrs(cx, &trait_item.attrs, trait_item.span, desc); + self.check_missing_docs_attrs(cx, &trait_item.attrs, cx.tcx.hir().span(trait_item.hir_id), desc); } fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, impl_item: &'tcx hir::ImplItem<'_>) { @@ -188,16 +188,16 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { hir::ImplItemKind::Fn(..) => "a method", hir::ImplItemKind::TyAlias(_) => "an associated type", }; - self.check_missing_docs_attrs(cx, &impl_item.attrs, impl_item.span, desc); + self.check_missing_docs_attrs(cx, &impl_item.attrs, cx.tcx.hir().span(impl_item.hir_id), desc); } fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, sf: &'tcx hir::StructField<'_>) { if !sf.is_positional() { - self.check_missing_docs_attrs(cx, &sf.attrs, sf.span, "a struct field"); + self.check_missing_docs_attrs(cx, &sf.attrs, cx.tcx.hir().span(sf.hir_id), "a struct field"); } } fn check_variant(&mut self, cx: &LateContext<'a, 'tcx>, v: &'tcx hir::Variant<'_>) { - self.check_missing_docs_attrs(cx, &v.attrs, v.span, "a variant"); + self.check_missing_docs_attrs(cx, &v.attrs, cx.tcx.hir().span(v.id), "a variant"); } } diff --git a/src/tools/clippy/clippy_lints/src/missing_inline.rs b/src/tools/clippy/clippy_lints/src/missing_inline.rs index 1802470b1841e..32c885c2704fa 100644 --- a/src/tools/clippy/clippy_lints/src/missing_inline.rs +++ b/src/tools/clippy/clippy_lints/src/missing_inline.rs @@ -81,7 +81,7 @@ declare_lint_pass!(MissingInline => [MISSING_INLINE_IN_PUBLIC_ITEMS]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingInline { fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, it: &'tcx hir::Item<'_>) { - if rustc_middle::lint::in_external_macro(cx.sess(), it.span) || is_executable(cx) { + if rustc_middle::lint::in_external_macro(cx.sess(), cx.tcx.hir().span(it.hir_id)) || is_executable(cx) { return; } @@ -91,7 +91,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingInline { match it.kind { hir::ItemKind::Fn(..) => { let desc = "a function"; - check_missing_inline_attrs(cx, &it.attrs, it.span, desc); + check_missing_inline_attrs(cx, &it.attrs, cx.tcx.hir().span(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 @@ -106,7 +106,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingInline { // an impl is not provided let desc = "a default trait method"; let item = cx.tcx.hir().expect_trait_item(tit.id.hir_id); - check_missing_inline_attrs(cx, &item.attrs, item.span, desc); + check_missing_inline_attrs(cx, &item.attrs, cx.tcx.hir().span(item.hir_id), desc); } }, } @@ -131,7 +131,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingInline { fn check_impl_item(&mut self, cx: &LateContext<'a, '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(cx) { + if rustc_middle::lint::in_external_macro(cx.sess(), cx.tcx.hir().span(impl_item.hir_id)) || is_executable(cx) { return; } @@ -159,6 +159,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingInline { } } - check_missing_inline_attrs(cx, &impl_item.attrs, impl_item.span, desc); + check_missing_inline_attrs(cx, &impl_item.attrs, cx.tcx.hir().span(impl_item.hir_id), desc); } } diff --git a/src/tools/clippy/clippy_lints/src/mut_key.rs b/src/tools/clippy/clippy_lints/src/mut_key.rs index 0b9b7e1b8cc1b..30a210f7b1809 100644 --- a/src/tools/clippy/clippy_lints/src/mut_key.rs +++ b/src/tools/clippy/clippy_lints/src/mut_key.rs @@ -76,7 +76,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableKeyType { if let hir::PatKind::Wild = local.pat.kind { return; } - check_ty(cx, local.span, cx.tables.pat_ty(&*local.pat)); + check_ty(cx, cx.tcx.hir().span(local.hir_id), cx.tables.pat_ty(&*local.pat)); } } diff --git a/src/tools/clippy/clippy_lints/src/needless_borrow.rs b/src/tools/clippy/clippy_lints/src/needless_borrow.rs index 5880d1d610206..83b56dac1bb8c 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrow.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrow.rs @@ -80,7 +80,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrow { } } fn check_pat(&mut self, cx: &LateContext<'a, '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! { @@ -94,12 +95,12 @@ impl<'a, 'tcx> LateLintPass<'a, '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 e56489c6d434d..0c07d53c65e38 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrowed_ref.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrowed_ref.rs @@ -54,7 +54,8 @@ declare_lint_pass!(NeedlessBorrowedRef => [NEEDLESS_BORROWED_REFERENCE]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrowedRef { fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat<'_>) { - if pat.span.from_expansion() { + let pat_span = cx.tcx.hir().span(pat.hir_id); + if pat_span.from_expansion() { // OK, simple enough, lints doesn't check in macro. return; } @@ -75,12 +76,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrowedRef { return; } let mut applicability = Applicability::MachineApplicable; - span_lint_and_then(cx, NEEDLESS_BORROWED_REFERENCE, pat.span, + span_lint_and_then(cx, NEEDLESS_BORROWED_REFERENCE, pat_span, "this pattern takes a reference on something that is being de-referenced", |diag| { let hint = snippet_with_applicability(cx, spanned_name.span, "..", &mut applicability).into_owned(); diag.span_suggestion( - pat.span, + pat_span, "try removing the `&ref` part and just keep", hint, applicability, diff --git a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs index ca87deac9891c..b86a225b1f55d 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<'a, 'tcx> LateLintPass<'a, '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/new_without_default.rs b/src/tools/clippy/clippy_lints/src/new_without_default.rs index dd236535c18ad..92360e61c07a8 100644 --- a/src/tools/clippy/clippy_lints/src/new_without_default.rs +++ b/src/tools/clippy/clippy_lints/src/new_without_default.rs @@ -66,7 +66,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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(impl_item.hir_id)) { return; } if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind { @@ -126,7 +126,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NewWithoutDefault { cx, NEW_WITHOUT_DEFAULT, id, - impl_item.span, + cx.tcx.hir().span(impl_item.hir_id), &format!( "you should consider adding a `Default` implementation for `{}`", self_ty @@ -134,7 +134,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NewWithoutDefault { |diag| { diag.suggest_prepend_item( cx, - item.span, + cx.tcx.hir().span(item.hir_id), "try this", &create_new_without_default_suggest_msg(self_ty), Applicability::MaybeIncorrect, diff --git a/src/tools/clippy/clippy_lints/src/no_effect.rs b/src/tools/clippy/clippy_lints/src/no_effect.rs index 2eacd3c80c486..da8e4d9443fbd 100644 --- a/src/tools/clippy/clippy_lints/src/no_effect.rs +++ b/src/tools/clippy/clippy_lints/src/no_effect.rs @@ -91,7 +91,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NoEffect { fn check_stmt(&mut self, cx: &LateContext<'a, '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 { @@ -108,7 +108,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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/non_copy_const.rs b/src/tools/clippy/clippy_lints/src/non_copy_const.rs index bb257e5a542d9..ff286d88e52e7 100644 --- a/src/tools/clippy/clippy_lints/src/non_copy_const.rs +++ b/src/tools/clippy/clippy_lints/src/non_copy_const.rs @@ -145,7 +145,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCopyConst { fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, it: &'tcx Item<'_>) { if let ItemKind::Const(hir_ty, ..) = &it.kind { let ty = hir_ty_to_ty(cx.tcx, hir_ty); - verify_ty_bound(cx, ty, Source::Item { item: it.span }); + verify_ty_bound(cx, ty, Source::Item { item: cx.tcx.hir().span(it.hir_id) }); } } @@ -157,7 +157,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCopyConst { ty, Source::Assoc { ty: hir_ty.span, - item: trait_item.span, + item: cx.tcx.hir().span(trait_item.hir_id), }, ); } @@ -175,7 +175,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCopyConst { ty, Source::Assoc { ty: hir_ty.span, - item: impl_item.span, + item: cx.tcx.hir().span(impl_item.hir_id), }, ); } 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 1445df41c452f..9c7b218be8c27 100644 --- a/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs +++ b/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs @@ -44,7 +44,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PartialEqNeImpl { cx, PARTIALEQ_NE_IMPL, impl_item.id.hir_id, - impl_item.span, + cx.tcx.hir().span(impl_item.id.hir_id), "re-implementing `PartialEq::ne` is unnecessary", ); } diff --git a/src/tools/clippy/clippy_lints/src/redundant_clone.rs b/src/tools/clippy/clippy_lints/src/redundant_clone.rs index d563eb886ae7e..220e29506d72a 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_clone.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_clone.rs @@ -17,7 +17,7 @@ use rustc_middle::ty::{self, fold::TypeVisitor, Ty}; use rustc_mir::dataflow::BottomValue; 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 std::convert::TryFrom; macro_rules! unwrap_or_continue { @@ -74,7 +74,6 @@ impl<'a, 'tcx> LateLintPass<'a, '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/redundant_pattern_matching.rs b/src/tools/clippy/clippy_lints/src/redundant_pattern_matching.rs index f16b916441ae8..46439a50db38f 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_pattern_matching.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_pattern_matching.rs @@ -100,7 +100,7 @@ fn find_sugg_for_if_let<'a, 'tcx>( 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 ... = ... { ... } 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 6fc07f91660ee..d77eea3aa6c95 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<'a, 'tcx> LateLintPass<'a, '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 def_id = cx.tcx.hir().local_def_id(item.hir_id); let descr = cx.tcx.def_kind(def_id).descr(def_id.to_def_id()); span_lint_and_then( diff --git a/src/tools/clippy/clippy_lints/src/serde_api.rs b/src/tools/clippy/clippy_lints/src/serde_api.rs index 6820d1620bd18..c7772ecd0f14d 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<'a, 'tcx> LateLintPass<'a, '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(item.id.hir_id)), + "visit_string" => seen_string = Some(cx.tcx.hir().span(item.id.hir_id)), _ => {}, } } diff --git a/src/tools/clippy/clippy_lints/src/shadow.rs b/src/tools/clippy/clippy_lints/src/shadow.rs index 68c36f9189184..7c07a804d7b3f 100644 --- a/src/tools/clippy/clippy_lints/src/shadow.rs +++ b/src/tools/clippy/clippy_lints/src/shadow.rs @@ -103,7 +103,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Shadow { _: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, - _: Span, _: HirId, ) { if in_external_macro(cx.sess(), body.value.span) { @@ -139,7 +138,8 @@ fn check_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, block: &'tcx Block<'_>, bin } fn check_local<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, local: &'tcx Local<'_>, bindings: &mut Vec<(Name, 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 +149,6 @@ fn check_local<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, local: &'tcx Local<'_>, bin ref pat, ref ty, ref init, - span, .. } = *local; if let Some(ref t) = *ty { @@ -190,7 +189,7 @@ fn check_pat<'a, '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; @@ -229,7 +228,7 @@ fn check_pat<'a, '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 { @@ -347,7 +346,7 @@ fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>, bindin 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 { diff --git a/src/tools/clippy/clippy_lints/src/swap.rs b/src/tools/clippy/clippy_lints/src/swap.rs index c52e6a643f2a2..2d727f4a9254a 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/trivially_copy_pass_by_ref.rs b/src/tools/clippy/clippy_lints/src/trivially_copy_pass_by_ref.rs index 8e0cb94317aff..d21743ad1564a 100644 --- a/src/tools/clippy/clippy_lints/src/trivially_copy_pass_by_ref.rs +++ b/src/tools/clippy/clippy_lints/src/trivially_copy_pass_by_ref.rs @@ -127,7 +127,7 @@ impl_lint_pass!(TriviallyCopyPassByRef => [TRIVIALLY_COPY_PASS_BY_REF]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TriviallyCopyPassByRef { fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem<'_>) { - if item.span.from_expansion() { + if cx.tcx.hir().span(item.hir_id).from_expansion() { return; } @@ -142,9 +142,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TriviallyCopyPassByRef { 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/types.rs b/src/tools/clippy/clippy_lints/src/types.rs index d59a2f1bae031..433cb86d36dfc 100644 --- a/src/tools/clippy/clippy_lints/src/types.rs +++ b/src/tools/clippy/clippy_lints/src/types.rs @@ -225,7 +225,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Types { _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, - _: Span, id: HirId, ) { // Skip trait implementations; see issue #605. @@ -604,7 +603,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnitValue { fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt<'_>) { if let StmtKind::Local(ref local) = stmt.kind { if is_unit(cx.tables.pat_ty(&local.pat)) { - if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() { + let stmt_span = cx.tcx.hir().span(stmt.hir_id); + if in_external_macro(cx.sess(), stmt_span) || cx.tcx.hir().span(local.pat.hir_id).from_expansion() { return; } if higher::is_from_for_desugar(local) { @@ -613,13 +613,13 @@ impl<'a, 'tcx> LateLintPass<'a, '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 @@ -827,7 +827,7 @@ fn lint_unit_args(cx: &LateContext<'_, '_>, expr: &Expr<'_>, args_to_recover: &[ if let Some(snip) = snippet_opt(cx, last_expr.span); then { Some(( - last_stmt.span, + cx.tcx.hir().span(last_stmt.hir_id), snip, )) } @@ -1644,7 +1644,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexity { _: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, _: &'tcx Body<'_>, - _: Span, _: HirId, ) { self.check_fndecl(cx, decl); @@ -2332,6 +2331,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher { return; } + let item_span = cx.tcx.hir().span(item.hir_id); + match item.kind { ItemKind::Impl { ref generics, @@ -2343,15 +2344,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher { vis.visit_ty(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 = 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; } @@ -2388,13 +2389,13 @@ impl<'a, 'tcx> LateLintPass<'a, '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)) + 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 3d5e2f9fd2155..4d6d56db3d326 100644 --- a/src/tools/clippy/clippy_lints/src/unused_self.rs +++ b/src/tools/clippy/clippy_lints/src/unused_self.rs @@ -41,7 +41,7 @@ declare_lint_pass!(UnusedSelf => [UNUSED_SELF]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedSelf { fn check_impl_item(&mut self, cx: &LateContext<'a, '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); @@ -67,7 +67,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedSelf { span_lint_and_help( cx, UNUSED_SELF, - self_param.span, + cx.tcx.hir().span(self_param.hir_id), "unused `self` argument", None, "consider refactoring to a associated function", diff --git a/src/tools/clippy/clippy_lints/src/unwrap.rs b/src/tools/clippy/clippy_lints/src/unwrap.rs index a6c7b5d405cda..7d6f9c61a0523 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap.rs @@ -10,7 +10,6 @@ use rustc_middle::hir::map::Map; use rustc_middle::lint::in_external_macro; use rustc_middle::ty::Ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::source_map::Span; declare_clippy_lint! { /// **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail. @@ -216,9 +215,9 @@ impl<'a, 'tcx> LateLintPass<'a, '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<'a, 'tcx> LateLintPass<'a, 'tcx> for Unwrap { unwrappables: Vec::new(), }; - walk_fn(&mut v, kind, decl, body.id(), span, fn_id); + walk_fn(&mut v, kind, decl, body.id(), fn_id); } } diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index f8e1aff33e773..a5d506a39abc6 100644 --- a/src/tools/clippy/clippy_lints/src/use_self.rs +++ b/src/tools/clippy/clippy_lints/src/use_self.rs @@ -159,7 +159,7 @@ fn check_trait_method_impl_decl<'a, 'tcx>( impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UseSelf { fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) { - if in_external_macro(cx.sess(), item.span) { + if in_external_macro(cx.sess(), cx.tcx.hir().span(item.hir_id)) { return; } if_chain! { 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 89e2bcdd7935d..7cab63e9ed66f 100644 --- a/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs +++ b/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs @@ -257,6 +257,7 @@ impl<'a, 'tcx> LateLintPass<'a, '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; @@ -277,15 +278,15 @@ impl<'a, 'tcx> LateLintPass<'a, '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 { of_trait: None, diff --git a/src/tools/clippy/clippy_lints/src/utils/mod.rs b/src/tools/clippy/clippy_lints/src/utils/mod.rs index 60ab19e71f5e4..3888585366b3a 100644 --- a/src/tools/clippy/clippy_lints/src/utils/mod.rs +++ b/src/tools/clippy/clippy_lints/src/utils/mod.rs @@ -463,7 +463,7 @@ struct ContainsName { impl<'tcx> Visitor<'tcx> for ContainsName { type Map = Map<'tcx>; - fn visit_name(&mut self, _: Span, name: Name) { + fn visit_name(&mut self, name: Name) { if self.name == name { self.result = true; } diff --git a/src/tools/clippy/clippy_lints/src/wildcard_imports.rs b/src/tools/clippy/clippy_lints/src/wildcard_imports.rs index b637253bd0264..7340be49a2889 100644 --- a/src/tools/clippy/clippy_lints/src/wildcard_imports.rs +++ b/src/tools/clippy/clippy_lints/src/wildcard_imports.rs @@ -111,7 +111,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.hir_id.owner); if !used_imports.is_empty(); // Already handled by `unused_imports` then { @@ -131,9 +131,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, @@ -188,8 +189,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) }