diff --git a/src/librustc_codegen_llvm/consts.rs b/src/librustc_codegen_llvm/consts.rs index 9d9b53fc4a87c..a70c77bf099d7 100644 --- a/src/librustc_codegen_llvm/consts.rs +++ b/src/librustc_codegen_llvm/consts.rs @@ -260,7 +260,7 @@ impl CodegenCx<'ll, 'tcx> { debug!("get_static: sym={} item_attr={:?}", sym, self.tcx.item_attrs(def_id)); let attrs = self.tcx.codegen_fn_attrs(def_id); - let span = self.tcx.def_span(def_id); + let span = self.tcx.real_def_span(def_id); let g = check_and_apply_linkage(&self, &attrs, ty, sym, span); // Thread-local statics in some other crate need to *always* be linked diff --git a/src/librustc_codegen_llvm/context.rs b/src/librustc_codegen_llvm/context.rs index 01f90cae7a5fc..1411994fa5539 100644 --- a/src/librustc_codegen_llvm/context.rs +++ b/src/librustc_codegen_llvm/context.rs @@ -18,7 +18,7 @@ use rustc_middle::ty::layout::{HasParamEnv, LayoutError, TyAndLayout}; use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; use rustc_session::config::{CFGuard, CrateType, DebugInfo}; use rustc_session::Session; -use rustc_span::source_map::{Span, DUMMY_SP}; +use rustc_span::source_map::{SpanId, DUMMY_SPID}; use rustc_span::symbol::Symbol; use rustc_target::abi::{HasDataLayout, LayoutOf, PointeeInfo, Size, TargetDataLayout, VariantIdx}; use rustc_target::spec::{HasTargetSpec, RelocModel, Target, TlsModel}; @@ -820,10 +820,10 @@ impl LayoutOf for CodegenCx<'ll, 'tcx> { type TyAndLayout = TyAndLayout<'tcx>; fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout { - self.spanned_layout_of(ty, DUMMY_SP) + self.spanned_layout_of(ty, DUMMY_SPID) } - fn spanned_layout_of(&self, ty: Ty<'tcx>, span: Span) -> Self::TyAndLayout { + fn spanned_layout_of(&self, ty: Ty<'tcx>, span: SpanId) -> Self::TyAndLayout { self.tcx.layout_of(ty::ParamEnv::reveal_all().and(ty)).unwrap_or_else(|e| { if let LayoutError::SizeOverflow(_) = e { self.sess().span_fatal(span, &e.to_string()) diff --git a/src/librustc_codegen_llvm/debuginfo/create_scope_map.rs b/src/librustc_codegen_llvm/debuginfo/create_scope_map.rs index 7f47b61de3f92..d2bc39594ca35 100644 --- a/src/librustc_codegen_llvm/debuginfo/create_scope_map.rs +++ b/src/librustc_codegen_llvm/debuginfo/create_scope_map.rs @@ -59,7 +59,7 @@ fn make_mir_scope( debug_context.scopes[parent] } else { // The root is the function itself. - let loc = cx.lookup_debug_loc(mir.span.lo()); + let loc = cx.lookup_debug_loc(cx.tcx.reify_span(mir.span).lo()); debug_context.scopes[scope] = DebugScope { scope_metadata: Some(fn_metadata), file_start_pos: loc.file.start_pos, @@ -75,7 +75,7 @@ fn make_mir_scope( return; } - let loc = cx.lookup_debug_loc(scope_data.span.lo()); + let loc = cx.lookup_debug_loc(cx.tcx.reify_span(scope_data.span).lo()); let file_metadata = file_metadata(cx, &loc.file, debug_context.defining_crate); let scope_metadata = unsafe { diff --git a/src/librustc_codegen_llvm/debuginfo/metadata.rs b/src/librustc_codegen_llvm/debuginfo/metadata.rs index fb9a27ed001f4..94b37e4bcc266 100644 --- a/src/librustc_codegen_llvm/debuginfo/metadata.rs +++ b/src/librustc_codegen_llvm/debuginfo/metadata.rs @@ -2313,7 +2313,7 @@ pub fn create_global_var_metadata(cx: &CodegenCx<'ll, '_>, def_id: DefId, global // We may want to remove the namespace scope if we're in an extern block (see // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952). let var_scope = get_namespace_for_item(cx, def_id); - let span = tcx.def_span(def_id); + let span = tcx.real_def_span(def_id); let (file_metadata, line_number) = if !span.is_dummy() { let loc = cx.lookup_debug_loc(span.lo()); diff --git a/src/librustc_codegen_llvm/debuginfo/mod.rs b/src/librustc_codegen_llvm/debuginfo/mod.rs index 8c9a2c09c272c..cf4790e8b5984 100644 --- a/src/librustc_codegen_llvm/debuginfo/mod.rs +++ b/src/librustc_codegen_llvm/debuginfo/mod.rs @@ -237,7 +237,7 @@ impl DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> { return None; } - let span = mir.span; + let span = self.tcx().reify_span(mir.span); // This can be the case for functions inlined from another crate if span.is_dummy() { diff --git a/src/librustc_codegen_ssa/back/write.rs b/src/librustc_codegen_ssa/back/write.rs index 6210559251def..38d73b6cf4013 100644 --- a/src/librustc_codegen_ssa/back/write.rs +++ b/src/librustc_codegen_ssa/back/write.rs @@ -1570,7 +1570,7 @@ impl SharedEmitter { } impl Emitter for SharedEmitter { - fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) { + fn emit_diagnostic(&mut self, diag: &rustc_errors::RealDiagnostic) { drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic { msg: diag.message(), code: diag.code.clone(), @@ -1612,7 +1612,7 @@ impl SharedEmitterMain { if let Some(code) = diag.code { d.code(code); } - handler.emit_diagnostic(&d); + handler.emit_diagnostic(d); } Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => { sess.span_err(ExpnId::from_u32(cookie).expn_data().call_site, &msg) diff --git a/src/librustc_codegen_ssa/base.rs b/src/librustc_codegen_ssa/base.rs index 29398db6ff8a9..84e3b2b6599a6 100644 --- a/src/librustc_codegen_ssa/base.rs +++ b/src/librustc_codegen_ssa/base.rs @@ -45,7 +45,7 @@ use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; use rustc_session::cgu_reuse_tracker::CguReuse; use rustc_session::config::{self, EntryFnType}; use rustc_session::Session; -use rustc_span::Span; +use rustc_span::SpanId; use rustc_symbol_mangling::test as symbol_names_test; use rustc_target::abi::{Abi, Align, LayoutOf, Scalar, VariantIdx}; @@ -414,7 +414,7 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( cx: &'a Bx::CodegenCx, - sp: Span, + sp: SpanId, rust_main: Bx::Value, rust_main_def_id: LocalDefId, use_start_lang_item: bool, diff --git a/src/librustc_codegen_ssa/mir/analyze.rs b/src/librustc_codegen_ssa/mir/analyze.rs index 9fcaf2818e831..79920b0014dea 100644 --- a/src/librustc_codegen_ssa/mir/analyze.rs +++ b/src/librustc_codegen_ssa/mir/analyze.rs @@ -224,7 +224,7 @@ impl<'mir, 'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> Visitor<'tcx> if let Some(index) = place.as_local() { self.assign(index, location); let decl_span = self.fx.mir.local_decls[index].source_info.span; - if !self.fx.rvalue_creates_operand(rvalue, decl_span) { + if !self.fx.rvalue_creates_operand(rvalue, self.fx.cx.tcx().reify_span(decl_span)) { self.not_ssa(index); } } else { diff --git a/src/librustc_codegen_ssa/mir/block.rs b/src/librustc_codegen_ssa/mir/block.rs index dfb1656a6e0cb..e3d380b7ecec1 100644 --- a/src/librustc_codegen_ssa/mir/block.rs +++ b/src/librustc_codegen_ssa/mir/block.rs @@ -406,6 +406,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { self.set_debug_loc(&mut bx, terminator.source_info); // Get the location information. + let span = bx.tcx().reify_span(span); let location = self.get_caller_location(&mut bx, span).immediate(); // Put together the arguments to the panic entry point. @@ -606,6 +607,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bug!("`miri_start_panic` should never end up in compiled code"); } + let span = bx.tcx().reify_span(span); if self.codegen_panic_intrinsic( &helper, &mut bx, @@ -670,7 +672,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let c = self.eval_mir_constant(constant); let (llval, ty) = self.simd_shuffle_indices( &bx, - constant.span, + bx.tcx().reify_span(constant.span), constant.literal.ty, c, ); @@ -689,7 +691,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { &fn_abi, &args, dest, - terminator.source_info.span, + bx.tcx().reify_span(terminator.source_info.span), ); if let ReturnDest::IndirectOperand(dst, _) = ret_dest { diff --git a/src/librustc_codegen_ssa/mir/debuginfo.rs b/src/librustc_codegen_ssa/mir/debuginfo.rs index 5501ed5128d4d..d3e1f5187cf08 100644 --- a/src/librustc_codegen_ssa/mir/debuginfo.rs +++ b/src/librustc_codegen_ssa/mir/debuginfo.rs @@ -1,3 +1,4 @@ +use crate::rustc_middle::ty::layout::HasTyCtxt; use crate::traits::*; use rustc_hir::def_id::CrateNum; use rustc_index::vec::IndexVec; @@ -60,23 +61,28 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } pub fn debug_loc(&self, source_info: mir::SourceInfo) -> (Option, Span) { + let source_span = self.cx.tcx().reify_span(source_info.span); + // Bail out if debug info emission is not enabled. match self.debug_context { - None => return (None, source_info.span), + None => return (None, source_span), Some(_) => {} } // In order to have a good line stepping behavior in debugger, we overwrite debug // locations of macro expansions with that of the outermost expansion site // (unless the crate is being compiled with `-Z debug-macros`). - if !source_info.span.from_expansion() || self.cx.sess().opts.debugging_opts.debug_macros { - let scope = self.scope_metadata_for_loc(source_info.scope, source_info.span.lo()); - (scope, source_info.span) + if !source_span.from_expansion() || self.cx.sess().opts.debugging_opts.debug_macros { + let scope = self.scope_metadata_for_loc(source_info.scope, source_span.lo()); + (scope, source_span) } else { // Walk up the macro expansion chain until we reach a non-expanded span. // We also stop at the function body level because no line stepping can occur // at the level above that. - let span = rustc_span::hygiene::walk_chain(source_info.span, self.mir.span.ctxt()); + let span = rustc_span::hygiene::walk_chain( + source_span, + self.cx.tcx().reify_span(self.mir.span).ctxt(), + ); let scope = self.scope_metadata_for_loc(source_info.scope, span.lo()); // Use span of the outermost expansion site, while keeping the original lexical scope. (scope, span) @@ -149,7 +155,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let (scope, span) = if full_debug_info { self.debug_loc(decl.source_info) } else { - (None, decl.source_info.span) + (None, self.cx.tcx().reify_span(decl.source_info.span)) }; let dbg_var = scope.map(|scope| { // FIXME(eddyb) is this `+ 1` needed at all? @@ -312,7 +318,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let (scope, span) = if full_debug_info { self.debug_loc(var.source_info) } else { - (None, var.source_info.span) + (None, self.cx.tcx().reify_span(var.source_info.span)) }; let dbg_var = scope.map(|scope| { let place = var.place; diff --git a/src/librustc_codegen_ssa/mir/rvalue.rs b/src/librustc_codegen_ssa/mir/rvalue.rs index bb532abd84bde..e02b1333f12ae 100644 --- a/src/librustc_codegen_ssa/mir/rvalue.rs +++ b/src/librustc_codegen_ssa/mir/rvalue.rs @@ -751,7 +751,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { mir::Rvalue::Aggregate(..) => { let ty = rvalue.ty(self.mir, self.cx.tcx()); let ty = self.monomorphize(&ty); - self.cx.spanned_layout_of(ty, span).is_zst() + self.cx.spanned_layout_of(ty, span.into()).is_zst() } } diff --git a/src/librustc_codegen_ssa/mir/statement.rs b/src/librustc_codegen_ssa/mir/statement.rs index ddd7447406c48..ba02a901cfee4 100644 --- a/src/librustc_codegen_ssa/mir/statement.rs +++ b/src/librustc_codegen_ssa/mir/statement.rs @@ -97,7 +97,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { &asm.asm, outputs, input_vals, - statement.source_info.span, + bx.tcx().reify_span(statement.source_info.span), ); if !res { struct_span_err!( diff --git a/src/librustc_codegen_ssa/traits/type_.rs b/src/librustc_codegen_ssa/traits/type_.rs index 703479b74bef8..d7ed924edb54f 100644 --- a/src/librustc_codegen_ssa/traits/type_.rs +++ b/src/librustc_codegen_ssa/traits/type_.rs @@ -5,7 +5,7 @@ use crate::common::TypeKind; use crate::mir::place::PlaceRef; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{self, Ty}; -use rustc_span::DUMMY_SP; +use rustc_span::DUMMY_SPID; use rustc_target::abi::call::{ArgAbi, CastTarget, FnAbi, Reg}; use rustc_target::abi::Integer; @@ -70,16 +70,16 @@ pub trait DerivedTypeMethods<'tcx>: BaseTypeMethods<'tcx> + MiscMethods<'tcx> { } fn type_is_sized(&self, ty: Ty<'tcx>) -> bool { - ty.is_sized(self.tcx().at(DUMMY_SP), ty::ParamEnv::reveal_all()) + ty.is_sized(self.tcx().at(DUMMY_SPID), ty::ParamEnv::reveal_all()) } fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool { - ty.is_freeze(self.tcx(), ty::ParamEnv::reveal_all(), DUMMY_SP) + ty.is_freeze(self.tcx(), ty::ParamEnv::reveal_all(), DUMMY_SPID) } fn type_has_metadata(&self, ty: Ty<'tcx>) -> bool { let param_env = ty::ParamEnv::reveal_all(); - if ty.is_sized(self.tcx().at(DUMMY_SP), param_env) { + if ty.is_sized(self.tcx().at(DUMMY_SPID), param_env) { return false; } diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 913ccf8e68089..ebd8e30d4f0fe 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -1173,7 +1173,7 @@ pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) { // it wants to print. if !info.payload().is::() { let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic"); - handler.emit_diagnostic(&d); + handler.emit_diagnostic(d); } let mut xs: Vec> = vec![ diff --git a/src/librustc_errors/annotate_snippet_emitter_writer.rs b/src/librustc_errors/annotate_snippet_emitter_writer.rs index d83175694f407..d810e9147fdb2 100644 --- a/src/librustc_errors/annotate_snippet_emitter_writer.rs +++ b/src/librustc_errors/annotate_snippet_emitter_writer.rs @@ -7,13 +7,13 @@ use crate::emitter::FileWithAnnotatedLines; use crate::snippet::Line; -use crate::{CodeSuggestion, Diagnostic, DiagnosticId, Emitter, Level, SubDiagnostic}; +use crate::{CodeSuggestion, DiagnosticId, Emitter, Level, RealDiagnostic, RealSubDiagnostic}; use annotate_snippets::display_list::DisplayList; use annotate_snippets::formatter::DisplayListFormatter; use annotate_snippets::snippet::*; use rustc_data_structures::sync::Lrc; use rustc_span::source_map::SourceMap; -use rustc_span::{Loc, MultiSpan, SourceFile}; +use rustc_span::{Loc, MultiSpan, SourceFile, Span}; /// Generates diagnostics using annotate-snippet pub struct AnnotateSnippetEmitterWriter { @@ -28,7 +28,7 @@ pub struct AnnotateSnippetEmitterWriter { impl Emitter for AnnotateSnippetEmitterWriter { /// The entry point for the diagnostics generation - fn emit_diagnostic(&mut self, diag: &Diagnostic) { + fn emit_diagnostic(&mut self, diag: &RealDiagnostic) { let mut children = diag.children.clone(); let (mut primary_span, suggestions) = self.primary_span_formatted(&diag); @@ -68,9 +68,9 @@ struct DiagnosticConverter<'a> { code: Option, msp: MultiSpan, #[allow(dead_code)] - children: &'a [SubDiagnostic], + children: &'a [RealSubDiagnostic], #[allow(dead_code)] - suggestions: &'a [CodeSuggestion], + suggestions: &'a [CodeSuggestion], } impl<'a> DiagnosticConverter<'a> { @@ -191,8 +191,8 @@ impl AnnotateSnippetEmitterWriter { message: String, code: &Option, msp: &MultiSpan, - children: &[SubDiagnostic], - suggestions: &[CodeSuggestion], + children: &[RealSubDiagnostic], + suggestions: &[CodeSuggestion], ) { let converter = DiagnosticConverter { source_map: self.source_map.clone(), diff --git a/src/librustc_errors/diagnostic.rs b/src/librustc_errors/diagnostic.rs index 1cc5daafed14e..a46e97c4312bf 100644 --- a/src/librustc_errors/diagnostic.rs +++ b/src/librustc_errors/diagnostic.rs @@ -5,18 +5,18 @@ use crate::Level; use crate::Substitution; use crate::SubstitutionPart; use crate::SuggestionStyle; -use rustc_span::{MultiSpan, Span, DUMMY_SP}; +use rustc_span::{Multi, SpanLike}; use std::fmt; #[must_use] #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)] -pub struct Diagnostic { +pub struct Diagnostic { pub level: Level, pub message: Vec<(String, Style)>, pub code: Option, - pub span: MultiSpan, - pub children: Vec, - pub suggestions: Vec, + pub span: Multi, + pub children: Vec>, + pub suggestions: Vec>, /// This is not used for highlighting or rendering any error message. Rather, it can be used /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of @@ -32,11 +32,11 @@ pub enum DiagnosticId { /// For example a note attached to an error. #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)] -pub struct SubDiagnostic { +pub struct SubDiagnostic { pub level: Level, pub message: Vec<(String, Style)>, - pub span: MultiSpan, - pub render_span: Option, + pub span: Multi, + pub render_span: Option>, } #[derive(Debug, PartialEq, Eq)] @@ -86,7 +86,7 @@ impl StringPart { } } -impl Diagnostic { +impl Diagnostic { pub fn new(level: Level, message: &str) -> Self { Diagnostic::new_with_code(level, None, message) } @@ -96,10 +96,10 @@ impl Diagnostic { level, message: vec![(message.to_owned(), Style::NoStyle)], code, - span: MultiSpan::new(), + span: Multi::new(), children: vec![], suggestions: vec![], - sort_span: DUMMY_SP, + sort_span: Span::default(), } } @@ -135,17 +135,18 @@ impl Diagnostic { /// all, and you just supplied a `Span` to create the diagnostic, /// then the snippet will just include that `Span`, which is /// called the primary span. - pub fn span_label>(&mut self, span: Span, label: T) -> &mut Self { - self.span.push_span_label(span, label.into()); + pub fn span_label>(&mut self, span: impl Into, label: T) -> &mut Self { + self.span.push_span_label(span.into(), label.into()); self } - pub fn replace_span_with(&mut self, after: Span) -> &mut Self { + pub fn replace_span_with(&mut self, after: impl Into) -> &mut Self { + let after = after.into(); let before = self.span.clone(); - self.set_span(after); + self.set_span(after.clone()); for span_label in before.span_labels() { if let Some(label) = span_label.label { - self.span_label(after, label); + self.span_label(after.clone(), label); } } self @@ -230,39 +231,39 @@ impl Diagnostic { } pub fn note(&mut self, msg: &str) -> &mut Self { - self.sub(Level::Note, msg, MultiSpan::new(), None); + self.sub(Level::Note, msg, Multi::new(), None); self } pub fn highlighted_note(&mut self, msg: Vec<(String, Style)>) -> &mut Self { - self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None); + self.sub_with_highlights(Level::Note, msg, Multi::new(), None); self } /// Prints the span with a note above it. - pub fn span_note>(&mut self, sp: S, msg: &str) -> &mut Self { + pub fn span_note>>(&mut self, sp: S, msg: &str) -> &mut Self { self.sub(Level::Note, msg, sp.into(), None); self } pub fn warn(&mut self, msg: &str) -> &mut Self { - self.sub(Level::Warning, msg, MultiSpan::new(), None); + self.sub(Level::Warning, msg, Multi::new(), None); self } /// Prints the span with a warn above it. - pub fn span_warn>(&mut self, sp: S, msg: &str) -> &mut Self { + pub fn span_warn>>(&mut self, sp: S, msg: &str) -> &mut Self { self.sub(Level::Warning, msg, sp.into(), None); self } pub fn help(&mut self, msg: &str) -> &mut Self { - self.sub(Level::Help, msg, MultiSpan::new(), None); + self.sub(Level::Help, msg, Multi::new(), None); self } /// Prints the span with some help above it. - pub fn span_help>(&mut self, sp: S, msg: &str) -> &mut Self { + pub fn span_help>>(&mut self, sp: S, msg: &str) -> &mut Self { self.sub(Level::Help, msg, sp.into(), None); self } @@ -270,14 +271,14 @@ impl Diagnostic { pub fn multipart_suggestion( &mut self, msg: &str, - suggestion: Vec<(Span, String)>, + suggestion: impl IntoIterator, String)>, applicability: Applicability, ) -> &mut Self { self.suggestions.push(CodeSuggestion { substitutions: vec![Substitution { parts: suggestion .into_iter() - .map(|(span, snippet)| SubstitutionPart { snippet, span }) + .map(|(span, snippet)| SubstitutionPart { snippet, span: span.into() }) .collect(), }], msg: msg.to_owned(), @@ -296,14 +297,14 @@ impl Diagnostic { pub fn tool_only_multipart_suggestion( &mut self, msg: &str, - suggestion: Vec<(Span, String)>, + suggestion: impl IntoIterator, String)>, applicability: Applicability, ) -> &mut Self { self.suggestions.push(CodeSuggestion { substitutions: vec![Substitution { parts: suggestion .into_iter() - .map(|(span, snippet)| SubstitutionPart { snippet, span }) + .map(|(span, snippet)| SubstitutionPart { snippet, span: span.into() }) .collect(), }], msg: msg.to_owned(), @@ -393,7 +394,9 @@ impl Diagnostic { ) -> &mut Self { self.suggestions.push(CodeSuggestion { substitutions: suggestions - .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] }) + .map(|snippet| Substitution { + parts: vec![SubstitutionPart { snippet, span: sp.clone() }], + }) .collect(), msg: msg.to_owned(), style: SuggestionStyle::ShowCode, @@ -467,7 +470,7 @@ impl Diagnostic { self } - pub fn set_span>(&mut self, sp: S) -> &mut Self { + pub fn set_span>>(&mut self, sp: S) -> &mut Self { self.span = sp.into(); if let Some(span) = self.span.primary_span() { self.sort_span = span; @@ -504,7 +507,7 @@ impl Diagnostic { /// Used by a lint. Copies over all details *but* the "main /// message". - pub fn copy_details_not_message(&mut self, from: &Diagnostic) { + pub fn copy_details_not_message(&mut self, from: &Diagnostic) { self.span = from.span.clone(); self.code = from.code.clone(); self.children.extend(from.children.iter().cloned()) @@ -516,13 +519,13 @@ impl Diagnostic { &mut self, level: Level, message: &str, - span: MultiSpan, - render_span: Option, + span: impl Into>, + render_span: Option>, ) { let sub = SubDiagnostic { level, message: vec![(message.to_owned(), Style::NoStyle)], - span, + span: span.into(), render_span, }; self.children.push(sub); @@ -534,15 +537,15 @@ impl Diagnostic { &mut self, level: Level, message: Vec<(String, Style)>, - span: MultiSpan, - render_span: Option, + span: Multi, + render_span: Option>, ) { let sub = SubDiagnostic { level, message, span, render_span }; self.children.push(sub); } } -impl SubDiagnostic { +impl SubDiagnostic { pub fn message(&self) -> String { self.message.iter().map(|i| i.0.as_str()).collect::() } @@ -551,3 +554,28 @@ impl SubDiagnostic { &self.message } } + +impl Diagnostic { + pub fn map_span(self, f: impl Fn(S) -> S2) -> Diagnostic { + Diagnostic { + level: self.level, + message: self.message, + code: self.code, + span: self.span.map_span(&f), + children: self.children.into_iter().map(|c| c.map_span(&f)).collect(), + suggestions: self.suggestions.into_iter().map(|s| s.map_span(&f)).collect(), + sort_span: f(self.sort_span), + } + } +} + +impl SubDiagnostic { + pub fn map_span(self, f: impl Fn(S) -> S2) -> SubDiagnostic { + SubDiagnostic { + level: self.level, + message: self.message, + span: self.span.map_span(&f), + render_span: self.render_span.map(|ms| ms.map_span(f)), + } + } +} diff --git a/src/librustc_errors/diagnostic_builder.rs b/src/librustc_errors/diagnostic_builder.rs index 2dbd9f4e52fad..13864b6828e48 100644 --- a/src/librustc_errors/diagnostic_builder.rs +++ b/src/librustc_errors/diagnostic_builder.rs @@ -2,7 +2,7 @@ use crate::{Applicability, Handler, Level, StashKey}; use crate::{Diagnostic, DiagnosticId, DiagnosticStyledString}; use log::debug; -use rustc_span::{MultiSpan, Span}; +use rustc_span::{MultiSpanId, SpanId}; use std::fmt::{self, Debug}; use std::ops::{Deref, DerefMut}; use std::thread::panicking; @@ -62,18 +62,18 @@ macro_rules! forward { } }; - // Forward pattern for &mut self -> &mut Self, with S: Into + // Forward pattern for &mut self -> &mut Self, with S: Into // type parameter. No obvious way to make this more generic. ( $(#[$attrs:meta])* - pub fn $n:ident>( + pub fn $n:ident>( &mut self, $($name:ident: $ty:ty),* $(,)? ) -> &mut Self ) => { $(#[$attrs])* - pub fn $n>(&mut self, $($name: $ty),*) -> &mut Self { + pub fn $n>(&mut self, $($name: $ty),*) -> &mut Self { self.0.diagnostic.$n($($name),*); self } @@ -97,8 +97,8 @@ impl<'a> DerefMut for DiagnosticBuilder<'a> { impl<'a> DiagnosticBuilder<'a> { /// Emit the diagnostic. pub fn emit(&mut self) { - self.0.handler.emit_diagnostic(&self); - self.cancel(); + let diag = std::mem::replace(&mut self.0.diagnostic, Diagnostic::new(Level::Cancelled, "")); + self.0.handler.emit_diagnostic(diag); } /// Emit the diagnostic unless `delay` is true, @@ -118,9 +118,9 @@ impl<'a> DiagnosticBuilder<'a> { /// the provided `span` and `key` through `.steal_diagnostic` on `Handler`. /// /// As with `buffer`, this is unless the handler has disabled such buffering. - pub fn stash(self, span: Span, key: StashKey) { + pub fn stash(self, span: impl Into, key: StashKey) { if let Some((diag, handler)) = self.into_diagnostic() { - handler.stash_diagnostic(span, key, diag); + handler.stash_diagnostic(span.into(), key, diag); } } @@ -156,13 +156,13 @@ impl<'a> DiagnosticBuilder<'a> { /// Convenience function for internal use, clients should use one of the /// span_* methods instead. - pub fn sub>( + pub fn sub>( &mut self, level: Level, message: &str, span: Option, ) -> &mut Self { - let span = span.map(|s| s.into()).unwrap_or_else(MultiSpan::new); + let span = span.map(|s| s.into()).unwrap_or_else(MultiSpanId::new); self.0.diagnostic.sub(level, message, span, None); self } @@ -179,18 +179,18 @@ impl<'a> DiagnosticBuilder<'a> { /// locally in whichever way makes the most sense. pub fn delay_as_bug(&mut self) { self.level = Level::Bug; - self.0.handler.delay_as_bug(self.0.diagnostic.clone()); - self.cancel(); + let diag = std::mem::replace(&mut self.0.diagnostic, Diagnostic::new(Level::Cancelled, "")); + self.0.handler.delay_as_bug(diag); } /// Adds a span/label to be included in the resulting snippet. - /// This is pushed onto the `MultiSpan` that was created when the + /// This is pushed onto the `MultiSpanId` that was created when the /// diagnostic was first built. If you don't call this function at - /// all, and you just supplied a `Span` to create the diagnostic, - /// then the snippet will just include that `Span`, which is + /// all, and you just supplied a `SpanId` to create the diagnostic, + /// then the snippet will just include that `SpanId`, which is /// called the primary span. - pub fn span_label(&mut self, span: Span, label: impl Into) -> &mut Self { - self.0.diagnostic.span_label(span, label); + pub fn span_label(&mut self, span: impl Into, label: impl Into) -> &mut Self { + self.0.diagnostic.span_label(span.into(), label); self } @@ -198,12 +198,12 @@ impl<'a> DiagnosticBuilder<'a> { /// See `span_label` for more information. pub fn span_labels( &mut self, - spans: impl IntoIterator, + spans: impl IntoIterator>, label: impl AsRef, ) -> &mut Self { let label = label.as_ref(); for span in spans { - self.0.diagnostic.span_label(span, label); + self.0.diagnostic.span_label(span.into(), label); } self } @@ -233,15 +233,15 @@ impl<'a> DiagnosticBuilder<'a> { ) -> &mut Self); forward!(pub fn note(&mut self, msg: &str) -> &mut Self); - forward!(pub fn span_note>( + forward!(pub fn span_note>( &mut self, sp: S, msg: &str, ) -> &mut Self); forward!(pub fn warn(&mut self, msg: &str) -> &mut Self); - forward!(pub fn span_warn>(&mut self, sp: S, msg: &str) -> &mut Self); + forward!(pub fn span_warn>(&mut self, sp: S, msg: &str) -> &mut Self); forward!(pub fn help(&mut self, msg: &str) -> &mut Self); - forward!(pub fn span_help>( + forward!(pub fn span_help>( &mut self, sp: S, msg: &str, @@ -250,7 +250,7 @@ impl<'a> DiagnosticBuilder<'a> { pub fn multipart_suggestion( &mut self, msg: &str, - suggestion: Vec<(Span, String)>, + suggestion: impl IntoIterator, String)>, applicability: Applicability, ) -> &mut Self { if !self.0.allow_suggestions { @@ -263,7 +263,7 @@ impl<'a> DiagnosticBuilder<'a> { pub fn tool_only_multipart_suggestion( &mut self, msg: &str, - suggestion: Vec<(Span, String)>, + suggestion: impl IntoIterator, String)>, applicability: Applicability, ) -> &mut Self { if !self.0.allow_suggestions { @@ -275,7 +275,7 @@ impl<'a> DiagnosticBuilder<'a> { pub fn span_suggestion( &mut self, - sp: Span, + sp: impl Into, msg: &str, suggestion: String, applicability: Applicability, @@ -283,13 +283,13 @@ impl<'a> DiagnosticBuilder<'a> { if !self.0.allow_suggestions { return self; } - self.0.diagnostic.span_suggestion(sp, msg, suggestion, applicability); + self.0.diagnostic.span_suggestion(sp.into(), msg, suggestion, applicability); self } pub fn span_suggestions( &mut self, - sp: Span, + sp: impl Into, msg: &str, suggestions: impl Iterator, applicability: Applicability, @@ -297,13 +297,13 @@ impl<'a> DiagnosticBuilder<'a> { if !self.0.allow_suggestions { return self; } - self.0.diagnostic.span_suggestions(sp, msg, suggestions, applicability); + self.0.diagnostic.span_suggestions(sp.into(), msg, suggestions, applicability); self } pub fn span_suggestion_short( &mut self, - sp: Span, + sp: impl Into, msg: &str, suggestion: String, applicability: Applicability, @@ -311,13 +311,13 @@ impl<'a> DiagnosticBuilder<'a> { if !self.0.allow_suggestions { return self; } - self.0.diagnostic.span_suggestion_short(sp, msg, suggestion, applicability); + self.0.diagnostic.span_suggestion_short(sp.into(), msg, suggestion, applicability); self } pub fn span_suggestion_verbose( &mut self, - sp: Span, + sp: impl Into, msg: &str, suggestion: String, applicability: Applicability, @@ -325,13 +325,13 @@ impl<'a> DiagnosticBuilder<'a> { if !self.0.allow_suggestions { return self; } - self.0.diagnostic.span_suggestion_verbose(sp, msg, suggestion, applicability); + self.0.diagnostic.span_suggestion_verbose(sp.into(), msg, suggestion, applicability); self } pub fn span_suggestion_hidden( &mut self, - sp: Span, + sp: impl Into, msg: &str, suggestion: String, applicability: Applicability, @@ -339,13 +339,13 @@ impl<'a> DiagnosticBuilder<'a> { if !self.0.allow_suggestions { return self; } - self.0.diagnostic.span_suggestion_hidden(sp, msg, suggestion, applicability); + self.0.diagnostic.span_suggestion_hidden(sp.into(), msg, suggestion, applicability); self } pub fn tool_only_span_suggestion( &mut self, - sp: Span, + sp: impl Into, msg: &str, suggestion: String, applicability: Applicability, @@ -353,11 +353,11 @@ impl<'a> DiagnosticBuilder<'a> { if !self.0.allow_suggestions { return self; } - self.0.diagnostic.tool_only_span_suggestion(sp, msg, suggestion, applicability); + self.0.diagnostic.tool_only_span_suggestion(sp.into(), msg, suggestion, applicability); self } - forward!(pub fn set_span>(&mut self, sp: S) -> &mut Self); + forward!(pub fn set_span>(&mut self, sp: S) -> &mut Self); forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self); pub fn allow_suggestions(&mut self, allow: bool) -> &mut Self { diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs index b22da86c09187..7cb3e69ea4d5d 100644 --- a/src/librustc_errors/emitter.rs +++ b/src/librustc_errors/emitter.rs @@ -15,7 +15,8 @@ use rustc_span::{MultiSpan, SourceFile, Span}; use crate::snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, Style, StyledString}; use crate::styled_buffer::StyledBuffer; use crate::{ - pluralize, CodeSuggestion, Diagnostic, DiagnosticId, Level, SubDiagnostic, SuggestionStyle, + pluralize, CodeSuggestion, DiagnosticId, Level, RealDiagnostic, RealSubDiagnostic, + SuggestionStyle, }; use log::*; @@ -181,7 +182,7 @@ const ANONYMIZED_LINE_NUM: &str = "LL"; /// Emitter trait for emitting errors. pub trait Emitter { /// Emit a structured diagnostic. - fn emit_diagnostic(&mut self, diag: &Diagnostic); + fn emit_diagnostic(&mut self, diag: &RealDiagnostic); /// Emit a notification that an artifact has been output. /// This is currently only supported for the JSON format, @@ -207,8 +208,8 @@ pub trait Emitter { /// we return the original `primary_span` and the original suggestions. fn primary_span_formatted<'a>( &mut self, - diag: &'a Diagnostic, - ) -> (MultiSpan, &'a [CodeSuggestion]) { + diag: &'a RealDiagnostic, + ) -> (MultiSpan, &'a [CodeSuggestion]) { let mut primary_span = diag.span.clone(); if let Some((sugg, rest)) = diag.suggestions.split_first() { if rest.is_empty() && @@ -276,7 +277,7 @@ pub trait Emitter { &self, source_map: &Option>, span: &mut MultiSpan, - children: &mut Vec, + children: &mut Vec, level: &Level, backtrace: bool, ) { @@ -314,7 +315,7 @@ pub trait Emitter { macro_kind.descr(), ); - children.push(SubDiagnostic { + children.push(RealSubDiagnostic { level: Level::Note, message: vec![(msg, Style::NoStyle)], span: MultiSpan::new(), @@ -327,7 +328,7 @@ pub trait Emitter { fn render_multispans_macro_backtrace( &self, span: &mut MultiSpan, - children: &mut Vec, + children: &mut Vec, backtrace: bool, ) { for span in iter::once(span).chain(children.iter_mut().map(|child| &mut child.span)) { @@ -417,7 +418,7 @@ pub trait Emitter { &self, source_map: &Option>, span: &mut MultiSpan, - children: &mut Vec, + children: &mut Vec, ) { debug!("fix_multispans_in_extern_macros: before: span={:?} children={:?}", span, children); for span in iter::once(&mut *span).chain(children.iter_mut().map(|child| &mut child.span)) { @@ -468,7 +469,7 @@ impl Emitter for EmitterWriter { self.sm.as_ref() } - fn emit_diagnostic(&mut self, diag: &Diagnostic) { + fn emit_diagnostic(&mut self, diag: &RealDiagnostic) { let mut children = diag.children.clone(); let (mut primary_span, suggestions) = self.primary_span_formatted(&diag); debug!("emit_diagnostic: suggestions={:?}", suggestions); @@ -503,7 +504,7 @@ impl Emitter for SilentEmitter { fn source_map(&self) -> Option<&Lrc> { None } - fn emit_diagnostic(&mut self, _: &Diagnostic) {} + fn emit_diagnostic(&mut self, _: &RealDiagnostic) {} } /// Maximum number of lines we will print for each error; arbitrary. @@ -1120,7 +1121,7 @@ impl EmitterWriter { max } - fn get_max_line_num(&mut self, span: &MultiSpan, children: &[SubDiagnostic]) -> usize { + fn get_max_line_num(&mut self, span: &MultiSpan, children: &[RealSubDiagnostic]) -> usize { let primary = self.get_multispan_max_line_num(span); children .iter() @@ -1522,7 +1523,7 @@ impl EmitterWriter { fn emit_suggestion_default( &mut self, - suggestion: &CodeSuggestion, + suggestion: &CodeSuggestion, level: &Level, max_line_num_len: usize, ) -> io::Result<()> { @@ -1685,8 +1686,8 @@ impl EmitterWriter { message: &[(String, Style)], code: &Option, span: &MultiSpan, - children: &[SubDiagnostic], - suggestions: &[CodeSuggestion], + children: &[RealSubDiagnostic], + suggestions: &[CodeSuggestion], ) { let max_line_num_len = if self.ui_testing { ANONYMIZED_LINE_NUM.len() diff --git a/src/librustc_errors/json.rs b/src/librustc_errors/json.rs index 1382825922b0e..1f80bee5de856 100644 --- a/src/librustc_errors/json.rs +++ b/src/librustc_errors/json.rs @@ -14,7 +14,7 @@ use rustc_span::source_map::{FilePathMapping, SourceMap}; use crate::emitter::{Emitter, HumanReadableErrorType}; use crate::registry::Registry; use crate::{Applicability, DiagnosticId}; -use crate::{CodeSuggestion, SubDiagnostic}; +use crate::{CodeSuggestion, RealDiagnostic, RealSubDiagnostic}; use rustc_data_structures::sync::Lrc; use rustc_span::hygiene::ExpnData; @@ -98,7 +98,7 @@ impl JsonEmitter { } impl Emitter for JsonEmitter { - fn emit_diagnostic(&mut self, diag: &crate::Diagnostic) { + fn emit_diagnostic(&mut self, diag: &RealDiagnostic) { let data = Diagnostic::from_errors_diagnostic(diag, self); let result = if self.pretty { writeln!(&mut self.dst, "{}", as_pretty_json(&data)) @@ -220,7 +220,7 @@ struct ArtifactNotification<'a> { } impl Diagnostic { - fn from_errors_diagnostic(diag: &crate::Diagnostic, je: &JsonEmitter) -> Diagnostic { + fn from_errors_diagnostic(diag: &crate::RealDiagnostic, je: &JsonEmitter) -> Diagnostic { let sugg = diag.suggestions.iter().map(|sugg| Diagnostic { message: sugg.msg.clone(), code: None, @@ -268,7 +268,7 @@ impl Diagnostic { } } - fn from_sub_diagnostic(diag: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic { + fn from_sub_diagnostic(diag: &RealSubDiagnostic, je: &JsonEmitter) -> Diagnostic { Diagnostic { message: diag.message(), code: None, @@ -354,7 +354,7 @@ impl DiagnosticSpan { .collect() } - fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter) -> Vec { + fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter) -> Vec { suggestion .substitutions .iter() diff --git a/src/librustc_errors/lib.rs b/src/librustc_errors/lib.rs index e4a560e434aaa..72e3d338ee467 100644 --- a/src/librustc_errors/lib.rs +++ b/src/librustc_errors/lib.rs @@ -18,7 +18,7 @@ use rustc_data_structures::stable_hasher::StableHasher; use rustc_data_structures::sync::{self, Lock, Lrc}; use rustc_data_structures::AtomicRef; use rustc_span::source_map::SourceMap; -use rustc_span::{Loc, MultiSpan, Span}; +use rustc_span::{Loc, MultiSpanId, Span, SpanId}; use std::borrow::Cow; use std::panic; @@ -95,7 +95,7 @@ impl SuggestionStyle { } #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)] -pub struct CodeSuggestion { +pub struct CodeSuggestion { /// Each substitute can have multiple variants due to multiple /// applicable suggestions /// @@ -117,7 +117,7 @@ pub struct CodeSuggestion { /// Substitution { parts: vec![(0..7, "x.y")] }, /// ] /// ``` - pub substitutions: Vec, + pub substitutions: Vec>, pub msg: String, /// Visual representation of this suggestion. pub style: SuggestionStyle, @@ -131,20 +131,43 @@ pub struct CodeSuggestion { #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)] /// See the docs on `CodeSuggestion::substitutions` -pub struct Substitution { - pub parts: Vec, +pub struct Substitution { + pub parts: Vec>, } #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)] -pub struct SubstitutionPart { +pub struct SubstitutionPart { pub span: Span, pub snippet: String, } -impl CodeSuggestion { +impl CodeSuggestion { + pub fn map_span(self, f: impl Fn(S) -> S2) -> CodeSuggestion { + CodeSuggestion { + substitutions: self.substitutions.into_iter().map(|s| s.map_span(&f)).collect(), + msg: self.msg, + style: self.style, + applicability: self.applicability, + } + } +} + +impl Substitution { + pub fn map_span(self, f: impl Fn(S) -> S2) -> Substitution { + Substitution { parts: self.parts.into_iter().map(|p| p.map_span(&f)).collect() } + } +} + +impl SubstitutionPart { + pub fn map_span(self, f: impl Fn(S) -> S2) -> SubstitutionPart { + SubstitutionPart { span: f(self.span), snippet: self.snippet } + } +} + +impl CodeSuggestion { /// Returns the assembled code suggestions, whether they should be shown with an underline /// and whether the substitution only differs in capitalization. - pub fn splice_lines(&self, sm: &SourceMap) -> Vec<(String, Vec, bool)> { + pub fn splice_lines(&self, sm: &SourceMap) -> Vec<(String, Vec>, bool)> { use rustc_span::{CharPos, Pos}; fn push_trailing( @@ -272,9 +295,14 @@ impl fmt::Display for ExplicitBug { impl error::Error for ExplicitBug {} -pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic}; +pub use diagnostic::{DiagnosticId, DiagnosticStyledString}; pub use diagnostic_builder::DiagnosticBuilder; +pub type Diagnostic = diagnostic::Diagnostic; +pub type SubDiagnostic = diagnostic::Diagnostic; +pub type RealDiagnostic = diagnostic::Diagnostic; +pub type RealSubDiagnostic = diagnostic::SubDiagnostic; + /// A handler deals with errors and other compiler output. /// Certain errors (fatal, bug, unimpl) may cause immediate exit, /// others log errors for later reporting. @@ -314,7 +342,7 @@ struct HandlerInner { /// stolen by other stages (e.g. to improve them and add more information). /// The stashed diagnostics count towards the total error count. /// When `.abort_if_errors()` is called, these are also emitted. - stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>, + stashed_diagnostics: FxIndexMap<(SpanId, StashKey), Diagnostic>, /// The warning count, used for a recap upon finishing deduplicated_warn_count: usize, @@ -326,10 +354,15 @@ pub enum StashKey { ItemNoType, } -fn default_track_diagnostic(_: &Diagnostic) {} +fn default_track_diagnostic(d: Diagnostic) -> RealDiagnostic { + d.map_span(|s| match s { + SpanId::Span(s) => s, + SpanId::DefId(_) => panic!("Virtual spans require a TyCtxt."), + }) +} -pub static TRACK_DIAGNOSTICS: AtomicRef = - AtomicRef::new(&(default_track_diagnostic as fn(&_))); +pub static TRACK_DIAGNOSTICS: AtomicRef RealDiagnostic> = + AtomicRef::new(&(default_track_diagnostic as fn(_) -> _)); #[derive(Copy, Clone, Default)] pub struct HandlerFlags { @@ -359,8 +392,8 @@ impl Drop for HandlerInner { if !self.has_errors() { let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new()); let has_bugs = !bugs.is_empty(); - for bug in bugs { - self.emit_diagnostic(&bug); + for bug in bugs.into_iter() { + self.emit_diagnostic(bug); } if has_bugs { panic!("no errors encountered even though `delay_span_bug` issued"); @@ -457,7 +490,7 @@ impl Handler { } /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing. - pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) { + pub fn stash_diagnostic(&self, span: SpanId, key: StashKey, diag: Diagnostic) { let mut inner = self.inner.borrow_mut(); // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key. @@ -466,11 +499,15 @@ impl Handler { } /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key. - pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option> { + pub fn steal_diagnostic( + &self, + span: impl Into, + key: StashKey, + ) -> Option> { self.inner .borrow_mut() .stashed_diagnostics - .remove(&(span, key)) + .remove(&(span.into(), key)) .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag)) } @@ -488,7 +525,11 @@ impl Handler { } /// Construct a builder at the `Warning` level at the given `span` and with the `msg`. - pub fn struct_span_warn(&self, span: impl Into, msg: &str) -> DiagnosticBuilder<'_> { + pub fn struct_span_warn( + &self, + span: impl Into, + msg: &str, + ) -> DiagnosticBuilder<'_> { let mut result = self.struct_warn(msg); result.set_span(span); result @@ -498,7 +539,7 @@ impl Handler { /// Also include a code. pub fn struct_span_warn_with_code( &self, - span: impl Into, + span: impl Into, msg: &str, code: DiagnosticId, ) -> DiagnosticBuilder<'_> { @@ -517,7 +558,11 @@ impl Handler { } /// Construct a builder at the `Error` level at the given `span` and with the `msg`. - pub fn struct_span_err(&self, span: impl Into, msg: &str) -> DiagnosticBuilder<'_> { + pub fn struct_span_err( + &self, + span: impl Into, + msg: &str, + ) -> DiagnosticBuilder<'_> { let mut result = self.struct_err(msg); result.set_span(span); result @@ -526,7 +571,7 @@ impl Handler { /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`. pub fn struct_span_err_with_code( &self, - span: impl Into, + span: impl Into, msg: &str, code: DiagnosticId, ) -> DiagnosticBuilder<'_> { @@ -551,7 +596,7 @@ impl Handler { /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`. pub fn struct_span_fatal( &self, - span: impl Into, + span: impl Into, msg: &str, ) -> DiagnosticBuilder<'_> { let mut result = self.struct_fatal(msg); @@ -562,7 +607,7 @@ impl Handler { /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`. pub fn struct_span_fatal_with_code( &self, - span: impl Into, + span: impl Into, msg: &str, code: DiagnosticId, ) -> DiagnosticBuilder<'_> { @@ -581,14 +626,14 @@ impl Handler { DiagnosticBuilder::new(self, Level::Help, msg) } - pub fn span_fatal(&self, span: impl Into, msg: &str) -> FatalError { + pub fn span_fatal(&self, span: impl Into, msg: &str) -> FatalError { self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span); FatalError } pub fn span_fatal_with_code( &self, - span: impl Into, + span: impl Into, msg: &str, code: DiagnosticId, ) -> FatalError { @@ -596,41 +641,41 @@ impl Handler { FatalError } - pub fn span_err(&self, span: impl Into, msg: &str) { + pub fn span_err(&self, span: impl Into, msg: &str) { self.emit_diag_at_span(Diagnostic::new(Error, msg), span); } - pub fn span_err_with_code(&self, span: impl Into, msg: &str, code: DiagnosticId) { + pub fn span_err_with_code(&self, span: impl Into, msg: &str, code: DiagnosticId) { self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span); } - pub fn span_warn(&self, span: impl Into, msg: &str) { + pub fn span_warn(&self, span: impl Into, msg: &str) { self.emit_diag_at_span(Diagnostic::new(Warning, msg), span); } - pub fn span_warn_with_code(&self, span: impl Into, msg: &str, code: DiagnosticId) { + pub fn span_warn_with_code(&self, span: impl Into, msg: &str, code: DiagnosticId) { self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span); } - pub fn span_bug(&self, span: impl Into, msg: &str) -> ! { + pub fn span_bug(&self, span: impl Into, msg: &str) -> ! { self.inner.borrow_mut().span_bug(span, msg) } - pub fn delay_span_bug(&self, span: impl Into, msg: &str) { + pub fn delay_span_bug(&self, span: impl Into, msg: &str) { self.inner.borrow_mut().delay_span_bug(span, msg) } - pub fn span_bug_no_panic(&self, span: impl Into, msg: &str) { + pub fn span_bug_no_panic(&self, span: impl Into, msg: &str) { self.emit_diag_at_span(Diagnostic::new(Bug, msg), span); } - pub fn span_note_without_error(&self, span: impl Into, msg: &str) { + pub fn span_note_without_error(&self, span: impl Into, msg: &str) { self.emit_diag_at_span(Diagnostic::new(Note, msg), span); } - pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> { + pub fn span_note_diag(&self, span: impl Into, msg: &str) -> DiagnosticBuilder<'_> { let mut db = DiagnosticBuilder::new(self, Note, msg); - db.set_span(span); + db.set_span(span.into()); db } @@ -687,17 +732,18 @@ impl Handler { self.inner.borrow_mut().must_teach(code) } - pub fn force_print_diagnostic(&self, db: Diagnostic) { + pub fn force_print_diagnostic(&self, db: RealDiagnostic) { self.inner.borrow_mut().force_print_diagnostic(db) } - pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) { + pub fn emit_diagnostic(&self, diagnostic: Diagnostic) { self.inner.borrow_mut().emit_diagnostic(diagnostic) } - fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into) { + fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into) { let mut inner = self.inner.borrow_mut(); - inner.emit_diagnostic(diag.set_span(sp)); + diag.set_span(sp); + inner.emit_diagnostic(diag); } pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) { @@ -714,17 +760,17 @@ impl HandlerInner { self.taught_diagnostics.insert(code.clone()) } - fn force_print_diagnostic(&mut self, db: Diagnostic) { + fn force_print_diagnostic(&mut self, db: RealDiagnostic) { self.emitter.emit_diagnostic(&db); } /// Emit all stashed diagnostics. fn emit_stashed_diagnostics(&mut self) { let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::>(); - diags.iter().for_each(|diag| self.emit_diagnostic(diag)); + diags.into_iter().for_each(|diag| self.emit_diagnostic(diag)); } - fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) { + fn emit_diagnostic(&mut self, diagnostic: Diagnostic) { if diagnostic.cancelled() { return; } @@ -733,7 +779,7 @@ impl HandlerInner { return; } - (*TRACK_DIAGNOSTICS)(diagnostic); + let diagnostic = (*TRACK_DIAGNOSTICS)(diagnostic); if let Some(ref code) = diagnostic.code { self.emitted_diagnostic_codes.insert(code.clone()); @@ -750,7 +796,7 @@ impl HandlerInner { // Only emit the diagnostic if we've been asked to deduplicate and // haven't already emitted an equivalent diagnostic. if !(self.flags.deduplicate_diagnostics && already_emitted(self)) { - self.emitter.emit_diagnostic(diagnostic); + self.emitter.emit_diagnostic(&diagnostic); if diagnostic.is_error() { self.deduplicated_err_count += 1; } else if diagnostic.level == Warning { @@ -789,7 +835,7 @@ impl HandlerInner { match (errors.len(), warnings.len()) { (0, 0) => return, - (0, _) => self.emit_diagnostic(&Diagnostic::new(Level::Warning, &warnings)), + (0, _) => self.emit_diagnostic(Diagnostic::new(Level::Warning, &warnings)), (_, 0) => { let _ = self.fatal(&errors); } @@ -859,16 +905,17 @@ impl HandlerInner { } } - fn span_bug(&mut self, sp: impl Into, msg: &str) -> ! { + fn span_bug(&mut self, sp: impl Into, msg: &str) -> ! { self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp); panic!(ExplicitBug); } - fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into) { - self.emit_diagnostic(diag.set_span(sp)); + fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into) { + diag.set_span(sp); + self.emit_diagnostic(diag); } - fn delay_span_bug(&mut self, sp: impl Into, msg: &str) { + fn delay_span_bug(&mut self, sp: impl Into, msg: &str) { // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before // incrementing `err_count` by one, so we need to +1 the comparing. // FIXME: Would be nice to increment err_count in a more coherent way. @@ -882,7 +929,7 @@ impl HandlerInner { } fn failure(&mut self, msg: &str) { - self.emit_diagnostic(&Diagnostic::new(FailureNote, msg)); + self.emit_diagnostic(Diagnostic::new(FailureNote, msg)); } fn fatal(&mut self, msg: &str) -> FatalError { @@ -899,17 +946,17 @@ impl HandlerInner { if self.treat_err_as_bug() { self.bug(msg); } - self.emit_diagnostic(&Diagnostic::new(level, msg)); + self.emit_diagnostic(Diagnostic::new(level, msg)); } fn bug(&mut self, msg: &str) -> ! { - self.emit_diagnostic(&Diagnostic::new(Bug, msg)); + self.emit_diagnostic(Diagnostic::new(Bug, msg)); panic!(ExplicitBug); } fn delay_as_bug(&mut self, diagnostic: Diagnostic) { if self.flags.report_delayed_bugs { - self.emit_diagnostic(&diagnostic); + self.emit_diagnostic(diagnostic.clone()); } self.delayed_span_bugs.push(diagnostic); } diff --git a/src/librustc_expand/base.rs b/src/librustc_expand/base.rs index fe5bf6f82c6d3..8dd1f18567bbd 100644 --- a/src/librustc_expand/base.rs +++ b/src/librustc_expand/base.rs @@ -17,7 +17,7 @@ use rustc_span::edition::Edition; use rustc_span::hygiene::{AstPass, ExpnData, ExpnId, ExpnKind}; use rustc_span::source_map::SourceMap; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{FileName, MultiSpan, Span, DUMMY_SP}; +use rustc_span::{FileName, MultiSpanId, Span, DUMMY_SP}; use smallvec::{smallvec, SmallVec}; use std::default::Default; @@ -1014,7 +1014,7 @@ impl<'a> ExtCtxt<'a> { self.current_expansion.id.expansion_cause() } - pub fn struct_span_err>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> { + pub fn struct_span_err>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> { self.parse_sess.span_diagnostic.struct_span_err(sp, msg) } @@ -1023,13 +1023,13 @@ impl<'a> ExtCtxt<'a> { /// /// Compilation will be stopped in the near future (at the end of /// the macro expansion phase). - pub fn span_err>(&self, sp: S, msg: &str) { + pub fn span_err>(&self, sp: S, msg: &str) { self.parse_sess.span_diagnostic.span_err(sp, msg); } - pub fn span_warn>(&self, sp: S, msg: &str) { + pub fn span_warn>(&self, sp: S, msg: &str) { self.parse_sess.span_diagnostic.span_warn(sp, msg); } - pub fn span_bug>(&self, sp: S, msg: &str) -> ! { + pub fn span_bug>(&self, sp: S, msg: &str) -> ! { self.parse_sess.span_diagnostic.span_bug(sp, msg); } pub fn trace_macros_diag(&mut self) { diff --git a/src/librustc_expand/proc_macro_server.rs b/src/librustc_expand/proc_macro_server.rs index afc6dc36eb430..ee76c90fac1e5 100644 --- a/src/librustc_expand/proc_macro_server.rs +++ b/src/librustc_expand/proc_macro_server.rs @@ -634,7 +634,7 @@ impl server::Diagnostic for Rustc<'_> { diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None); } fn emit(&mut self, diag: Self::Diagnostic) { - self.sess.span_diagnostic.emit_diagnostic(&diag); + self.sess.span_diagnostic.emit_diagnostic(diag); } } diff --git a/src/librustc_infer/infer/error_reporting/mod.rs b/src/librustc_infer/infer/error_reporting/mod.rs index a8d6c01785ff9..c4defa8b4f8ba 100644 --- a/src/librustc_infer/infer/error_reporting/mod.rs +++ b/src/librustc_infer/infer/error_reporting/mod.rs @@ -1467,7 +1467,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> { fn visit_ty(&mut self, t: Ty<'tcx>) -> bool { if let Some((kind, def_id)) = TyCategory::from_ty(t) { - let span = self.tcx.def_span(def_id); + let span = self.tcx.real_def_span(def_id); // Avoid cluttering the output when the "found" and error span overlap: // // error[E0308]: mismatched types @@ -1543,7 +1543,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { self.tcx .sess .source_map() - .mk_substr_filename(self.tcx.def_span(*def_id)), + .mk_substr_filename(self.tcx.real_def_span(*def_id)), ), (true, _) => format!(" ({})", ty.sort_string(self.tcx)), (false, _) => "".to_string(), 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 d8133c58df7eb..d599d0f0268af 100644 --- a/src/librustc_infer/infer/error_reporting/need_type_info.rs +++ b/src/librustc_infer/infer/error_reporting/need_type_info.rs @@ -505,7 +505,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { .span .span_labels() .iter() - .any(|span_label| span_label.label.is_some() && span_label.span == span) + .any(|span_label| span_label.label.is_some() && span_label.span == span.into()) && local_visitor.found_arg_pattern.is_none() { // Avoid multiple labels pointing at `span`. diff --git a/src/librustc_infer/infer/error_reporting/nice_region_error/trait_impl_difference.rs b/src/librustc_infer/infer/error_reporting/nice_region_error/trait_impl_difference.rs index 695f3e47fb5d7..e2e75d142e2f1 100644 --- a/src/librustc_infer/infer/error_reporting/nice_region_error/trait_impl_difference.rs +++ b/src/librustc_infer/infer/error_reporting/nice_region_error/trait_impl_difference.rs @@ -6,7 +6,7 @@ use crate::infer::{Subtype, ValuePairs}; use crate::traits::ObligationCauseCode::CompareImplMethodObligation; use rustc_errors::ErrorReported; use rustc_middle::ty::Ty; -use rustc_span::Span; +use rustc_span::{Span, SpanId}; impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { /// Print the error message for lifetime errors when the `impl` doesn't conform to the `trait`. @@ -47,7 +47,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { None } - fn emit_err(&self, sp: Span, expected: Ty<'tcx>, found: Ty<'tcx>, impl_sp: Span) { + fn emit_err(&self, sp: Span, expected: Ty<'tcx>, found: Ty<'tcx>, impl_sp: SpanId) { let mut err = self .tcx() .sess diff --git a/src/librustc_infer/infer/lexical_region_resolve/mod.rs b/src/librustc_infer/infer/lexical_region_resolve/mod.rs index 3ff0e26a4dc38..f8bb51425a3bf 100644 --- a/src/librustc_infer/infer/lexical_region_resolve/mod.rs +++ b/src/librustc_infer/infer/lexical_region_resolve/mod.rs @@ -664,7 +664,7 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> { .iter() .map(|&choice_region| var_data.normalize(self.tcx(), choice_region)); if !choice_regions.clone().any(|choice_region| member_region == choice_region) { - let span = self.tcx().def_span(member_constraint.opaque_type_def_id); + let span = self.tcx().real_def_span(member_constraint.opaque_type_def_id); errors.push(RegionResolutionError::MemberConstraintFailure { span, hidden_ty: member_constraint.hidden_ty, diff --git a/src/librustc_infer/infer/mod.rs b/src/librustc_infer/infer/mod.rs index 67632a97df792..257bd617b92b1 100644 --- a/src/librustc_infer/infer/mod.rs +++ b/src/librustc_infer/infer/mod.rs @@ -33,7 +33,7 @@ use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt}; use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid}; use rustc_session::config::BorrowckMode; use rustc_span::symbol::Symbol; -use rustc_span::Span; +use rustc_span::{Span, SpanId}; use std::cell::{Cell, Ref, RefCell}; use std::collections::BTreeMap; @@ -1579,7 +1579,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { def_id: DefId, substs: SubstsRef<'tcx>, promoted: Option, - span: Option, + span: Option, ) -> ConstEvalResult<'tcx> { let mut original_values = OriginalQueryValues::default(); let canonical = self.canonicalize_query(&(param_env, substs), &mut original_values); diff --git a/src/librustc_infer/traits/util.rs b/src/librustc_infer/traits/util.rs index b34685006e223..71103773c08eb 100644 --- a/src/librustc_infer/traits/util.rs +++ b/src/librustc_infer/traits/util.rs @@ -4,7 +4,7 @@ use crate::traits::{Obligation, ObligationCause, PredicateObligation}; use rustc_data_structures::fx::FxHashSet; use rustc_middle::ty::outlives::Component; use rustc_middle::ty::{self, ToPolyTraitRef, ToPredicate, TyCtxt, WithConstness}; -use rustc_span::Span; +use rustc_span::SpanId; pub fn anonymize_predicate<'tcx>( tcx: TyCtxt<'tcx>, @@ -112,7 +112,8 @@ pub fn elaborate_predicates<'tcx>( tcx: TyCtxt<'tcx>, predicates: impl Iterator>, ) -> Elaborator<'tcx> { - let obligations = predicates.map(|predicate| predicate_obligation(predicate, None)).collect(); + let obligations = + predicates.map(|predicate| predicate_obligation(tcx, predicate, None)).collect(); elaborate_obligations(tcx, obligations) } @@ -126,12 +127,13 @@ pub fn elaborate_obligations<'tcx>( } fn predicate_obligation<'tcx>( + tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tcx>, - span: Option, + span: Option, ) -> PredicateObligation<'tcx> { let mut cause = ObligationCause::dummy(); if let Some(span) = span { - cause.span = span; + cause.span = tcx.reify_span(span); } Obligation { cause, param_env: ty::ParamEnv::empty(), recursion_depth: 0, predicate } } @@ -150,6 +152,7 @@ impl Elaborator<'tcx> { let obligations = predicates.predicates.iter().map(|(pred, span)| { predicate_obligation( + tcx, pred.subst_supertrait(tcx, &data.to_poly_trait_ref()), Some(*span), ) @@ -245,7 +248,7 @@ impl Elaborator<'tcx> { } }) .filter(|p| visited.insert(p)) - .map(|p| predicate_obligation(p, None)), + .map(|p| predicate_obligation(tcx, p, None)), ); } } diff --git a/src/librustc_interface/callbacks.rs b/src/librustc_interface/callbacks.rs index 913c67d045e59..ea357bd90a8e5 100644 --- a/src/librustc_interface/callbacks.rs +++ b/src/librustc_interface/callbacks.rs @@ -9,15 +9,16 @@ //! The functions in this file should fall back to the default set in their //! origin crate when the `TyCtxt` is not present in TLS. -use rustc_errors::{Diagnostic, TRACK_DIAGNOSTICS}; +use rustc_errors::{Diagnostic, RealDiagnostic, TRACK_DIAGNOSTICS}; use rustc_middle::ty::tls; use std::fmt; /// This is a callback from librustc_ast as it cannot access the implicit state /// in librustc_middle otherwise. -fn span_debug(span: rustc_span::Span, f: &mut fmt::Formatter<'_>) -> fmt::Result { +fn span_debug(span: rustc_span::SpanId, f: &mut fmt::Formatter<'_>) -> fmt::Result { tls::with_opt(|tcx| { if let Some(tcx) = tcx { + let span = tcx.reify_span(span); write!(f, "{}", tcx.sess.source_map().span_to_string(span)) } else { rustc_span::default_span_debug(span, f) @@ -28,13 +29,22 @@ fn span_debug(span: rustc_span::Span, f: &mut fmt::Formatter<'_>) -> fmt::Result /// This is a callback from librustc_ast as it cannot access the implicit state /// in librustc_middle otherwise. It is used to when diagnostic messages are /// emitted and stores them in the current query, if there is one. -fn track_diagnostic(diagnostic: &Diagnostic) { +fn track_diagnostic(diagnostic: Diagnostic) -> RealDiagnostic { tls::with_context_opt(|icx| { if let Some(icx) = icx { if let Some(ref diagnostics) = icx.diagnostics { let mut diagnostics = diagnostics.lock(); diagnostics.extend(Some(diagnostic.clone())); } + + // Ignore dependencies when reifying spans. + let icx = tls::ImplicitCtxt { task_deps: None, ..icx.clone() }; + tls::enter_context(&icx, |icx| diagnostic.map_span(|s| icx.tcx.reify_span(s))) + } else { + diagnostic.map_span(|s| match s { + rustc_span::SpanId::Span(s) => s, + rustc_span::SpanId::DefId(_) => panic!("Virtual spans require a TyCtxt."), + }) } }) } @@ -57,5 +67,5 @@ fn def_id_debug(def_id: rustc_hir::def_id::DefId, f: &mut fmt::Formatter<'_>) -> pub fn setup_callbacks() { rustc_span::SPAN_DEBUG.swap(&(span_debug as fn(_, &mut fmt::Formatter<'_>) -> _)); rustc_hir::def_id::DEF_ID_DEBUG.swap(&(def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _)); - TRACK_DIAGNOSTICS.swap(&(track_diagnostic as fn(&_))); + TRACK_DIAGNOSTICS.swap(&(track_diagnostic as fn(_) -> _)); } diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index 7d5289cd46f5b..fa20192766e36 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -42,7 +42,7 @@ use rustc_session::lint::FutureIncompatibleInfo; use rustc_span::edition::Edition; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{BytePos, Span}; +use rustc_span::{BytePos, Span, SpanId}; use rustc_target::abi::VariantIdx; use rustc_trait_selection::traits::misc::can_type_implement_copy; @@ -562,7 +562,7 @@ 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) { + if ty.is_copy_modulo_regions(cx.tcx, param_env, item.span.into()) { return; } if can_type_implement_copy(cx.tcx, param_env, ty).is_ok() { @@ -1133,7 +1133,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds { // The parameters must not have bounds for param in type_alias_generics.params.iter() { let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect(); - let suggestion = spans + let suggestion: Vec<_> = spans .iter() .map(|sp| { let start = param.span.between(*sp); // Include the `:` in `T: Bound`. @@ -1491,7 +1491,7 @@ declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMEN impl ExplicitOutlivesRequirements { fn lifetimes_outliving_lifetime<'tcx>( - inferred_outlives: &'tcx [(ty::Predicate<'tcx>, Span)], + inferred_outlives: &'tcx [(ty::Predicate<'tcx>, SpanId)], index: u32, ) -> Vec> { inferred_outlives @@ -1510,7 +1510,7 @@ impl ExplicitOutlivesRequirements { } fn lifetimes_outliving_type<'tcx>( - inferred_outlives: &'tcx [(ty::Predicate<'tcx>, Span)], + inferred_outlives: &'tcx [(ty::Predicate<'tcx>, SpanId)], index: u32, ) -> Vec> { inferred_outlives @@ -1529,7 +1529,7 @@ impl ExplicitOutlivesRequirements { &self, param: &'tcx hir::GenericParam<'tcx>, tcx: TyCtxt<'tcx>, - inferred_outlives: &'tcx [(ty::Predicate<'tcx>, Span)], + inferred_outlives: &'tcx [(ty::Predicate<'tcx>, SpanId)], ty_generics: &'tcx ty::Generics, ) -> Vec> { let index = @@ -1977,7 +1977,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidValue { if span.is_none() { // Point to this field, should be helpful for figuring // out where the source of the error is. - let span = tcx.def_span(field.did); + let span = tcx.real_def_span(field.did); write!( &mut msg, " (in this {} field)", diff --git a/src/librustc_lint/context.rs b/src/librustc_lint/context.rs index e5d3227d5afd4..413cdca872021 100644 --- a/src/librustc_lint/context.rs +++ b/src/librustc_lint/context.rs @@ -34,7 +34,7 @@ use rustc_middle::ty::{self, print::Printer, subst::GenericArg, Ty, TyCtxt}; use rustc_session::lint::{add_elided_lifetime_in_path_suggestion, BuiltinLintDiagnostics}; use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId}; use rustc_session::Session; -use rustc_span::{symbol::Symbol, MultiSpan, Span, DUMMY_SP}; +use rustc_span::{symbol::Symbol, MultiSpanId, Span, DUMMY_SP}; use rustc_target::abi::LayoutOf; use std::slice; @@ -477,7 +477,7 @@ pub trait LintContext: Sized { fn lookup_with_diagnostics( &self, lint: &'static Lint, - span: Option>, + span: Option>, decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), diagnostic: BuiltinLintDiagnostics, ) { @@ -576,16 +576,16 @@ pub trait LintContext: Sized { }); } - // FIXME: These methods should not take an Into -- instead, callers should need to + // FIXME: These methods should not take an Into -- instead, callers should need to // set the span in their `decorate` function (preferably using set_span). - fn lookup>( + fn lookup>( &self, lint: &'static Lint, span: Option, decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), ); - fn struct_span_lint>( + fn struct_span_lint>( &self, lint: &'static Lint, span: S, @@ -629,7 +629,7 @@ impl LintContext for LateContext<'_, '_> { &*self.lint_store } - fn lookup>( + fn lookup>( &self, lint: &'static Lint, span: Option, @@ -656,7 +656,7 @@ impl LintContext for EarlyContext<'_> { &*self.lint_store } - fn lookup>( + fn lookup>( &self, lint: &'static Lint, span: Option, diff --git a/src/librustc_lint/levels.rs b/src/librustc_lint/levels.rs index 274e57ae64cac..361e7372d8792 100644 --- a/src/librustc_lint/levels.rs +++ b/src/librustc_lint/levels.rs @@ -17,7 +17,7 @@ use rustc_middle::ty::TyCtxt; use rustc_session::lint::{builtin, Level, Lint}; use rustc_session::parse::feature_err; use rustc_session::Session; -use rustc_span::source_map::MultiSpan; +use rustc_span::source_map::MultiSpanId; use rustc_span::symbol::{sym, Symbol}; use std::cmp; @@ -398,7 +398,7 @@ impl<'s> LintLevelsBuilder<'s> { pub fn struct_lint( &self, lint: &'static Lint, - span: Option, + span: Option, decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), ) { let (level, src) = self.lint_level(lint); diff --git a/src/librustc_macros/src/query.rs b/src/librustc_macros/src/query.rs index 5f5bae66cfc65..a9262968cc36d 100644 --- a/src/librustc_macros/src/query.rs +++ b/src/librustc_macros/src/query.rs @@ -496,7 +496,7 @@ pub fn rustc_queries(input: TokenStream) -> TokenStream { force_query::, _>( $tcx, key, - DUMMY_SP, + DUMMY_SPID, *$dep_node ); return true; diff --git a/src/librustc_metadata/rmeta/decoder.rs b/src/librustc_metadata/rmeta/decoder.rs index 32149c0afd597..f46eaf5f1aa32 100644 --- a/src/librustc_metadata/rmeta/decoder.rs +++ b/src/librustc_metadata/rmeta/decoder.rs @@ -34,7 +34,7 @@ use rustc_serialize::{opaque, Decodable, Decoder, SpecializedDecoder}; use rustc_session::Session; use rustc_span::source_map::{respan, Spanned}; use rustc_span::symbol::{sym, Ident, Symbol}; -use rustc_span::{self, hygiene::MacroKind, BytePos, Pos, Span, DUMMY_SP}; +use rustc_span::{self, hygiene::MacroKind, BytePos, Pos, Span, SpanId, DUMMY_SP}; use log::debug; use proc_macro::bridge::client::ProcMacro; @@ -837,7 +837,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { &self, item_id: DefIndex, tcx: TyCtxt<'tcx>, - ) -> &'tcx [(ty::Predicate<'tcx>, Span)] { + ) -> &'tcx [(ty::Predicate<'tcx>, SpanId)] { self.root .tables .inferred_outlives diff --git a/src/librustc_metadata/rmeta/decoder/cstore_impl.rs b/src/librustc_metadata/rmeta/decoder/cstore_impl.rs index b18272675c0b2..1fa8b82859ce3 100644 --- a/src/librustc_metadata/rmeta/decoder/cstore_impl.rs +++ b/src/librustc_metadata/rmeta/decoder/cstore_impl.rs @@ -124,7 +124,7 @@ provide! { <'tcx> tcx, def_id, other, cdata, static_mutability => { cdata.static_mutability(def_id.index) } generator_kind => { cdata.generator_kind(def_id.index) } def_kind => { cdata.def_kind(def_id.index) } - def_span => { cdata.get_span(def_id.index, &tcx.sess) } + real_def_span => { cdata.get_span(def_id.index, &tcx.sess) } lookup_stability => { cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s)) } diff --git a/src/librustc_metadata/rmeta/encoder.rs b/src/librustc_metadata/rmeta/encoder.rs index 2589e162dffe2..abd12a8d8a0f9 100644 --- a/src/librustc_metadata/rmeta/encoder.rs +++ b/src/librustc_metadata/rmeta/encoder.rs @@ -253,10 +253,10 @@ impl<'tcx> SpecializedEncoder for EncodeContext<'tcx> { } } -impl<'tcx> SpecializedEncoder<&'tcx [(ty::Predicate<'tcx>, Span)]> for EncodeContext<'tcx> { +impl<'tcx> SpecializedEncoder<&'tcx [(ty::Predicate<'tcx>, SpanId)]> for EncodeContext<'tcx> { fn specialized_encode( &mut self, - predicates: &&'tcx [(ty::Predicate<'tcx>, Span)], + predicates: &&'tcx [(ty::Predicate<'tcx>, SpanId)], ) -> Result<(), Self::Error> { ty_codec::encode_spanned_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands) } @@ -622,7 +622,7 @@ impl EncodeContext<'tcx> { record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); record!(self.tables.visibility[def_id] <- ty::Visibility::from_hir(enum_vis, enum_id, self.tcx)); - record!(self.tables.span[def_id] <- self.tcx.def_span(def_id)); + record!(self.tables.span[def_id] <- self.tcx.real_def_span(def_id)); record!(self.tables.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]); record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| { assert!(f.did.is_local()); @@ -671,7 +671,7 @@ impl EncodeContext<'tcx> { record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); record!(self.tables.visibility[def_id] <- ctor_vis); - record!(self.tables.span[def_id] <- self.tcx.def_span(def_id)); + record!(self.tables.span[def_id] <- self.tcx.real_def_span(def_id)); self.encode_stability(def_id); self.encode_deprecation(def_id); self.encode_item_type(def_id); @@ -706,7 +706,7 @@ impl EncodeContext<'tcx> { record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data))); record!(self.tables.visibility[def_id] <- ty::Visibility::from_hir(vis, id, self.tcx)); - record!(self.tables.span[def_id] <- self.tcx.def_span(def_id)); + record!(self.tables.span[def_id] <- self.tcx.real_def_span(def_id)); record!(self.tables.attributes[def_id] <- attrs); record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| { tcx.hir().local_def_id(item_id.id).local_def_index @@ -733,7 +733,7 @@ impl EncodeContext<'tcx> { record!(self.tables.kind[def_id] <- EntryKind::Field); record!(self.tables.visibility[def_id] <- field.vis); - record!(self.tables.span[def_id] <- self.tcx.def_span(def_id)); + record!(self.tables.span[def_id] <- self.tcx.real_def_span(def_id)); record!(self.tables.attributes[def_id] <- variant_data.fields()[field_index].attrs); self.encode_ident_span(def_id, field.ident); self.encode_stability(def_id); @@ -774,7 +774,7 @@ impl EncodeContext<'tcx> { record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr)); record!(self.tables.visibility[def_id] <- ctor_vis); - record!(self.tables.span[def_id] <- self.tcx.def_span(def_id)); + record!(self.tables.span[def_id] <- self.tcx.real_def_span(def_id)); self.encode_stability(def_id); self.encode_deprecation(def_id); self.encode_item_type(def_id); @@ -1301,7 +1301,7 @@ impl EncodeContext<'tcx> { fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) { record!(self.tables.kind[def_id] <- kind); record!(self.tables.visibility[def_id] <- ty::Visibility::Public); - record!(self.tables.span[def_id] <- self.tcx.def_span(def_id)); + record!(self.tables.span[def_id] <- self.tcx.real_def_span(def_id)); if encode_type { self.encode_item_type(def_id); } @@ -1326,7 +1326,7 @@ impl EncodeContext<'tcx> { _ => bug!("closure that is neither generator nor closure"), }); record!(self.tables.visibility[def_id.to_def_id()] <- ty::Visibility::Public); - record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id)); + record!(self.tables.span[def_id.to_def_id()] <- self.tcx.real_def_span(def_id)); record!(self.tables.attributes[def_id.to_def_id()] <- &self.tcx.get_attrs(def_id.to_def_id())[..]); self.encode_item_type(def_id.to_def_id()); if let ty::Closure(def_id, substs) = ty.kind { @@ -1346,7 +1346,7 @@ impl EncodeContext<'tcx> { record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Const(qualifs, const_data)); record!(self.tables.visibility[def_id.to_def_id()] <- ty::Visibility::Public); - record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id)); + record!(self.tables.span[def_id.to_def_id()] <- self.tcx.real_def_span(def_id)); self.encode_item_type(def_id.to_def_id()); self.encode_generics(def_id.to_def_id()); self.encode_explicit_predicates(def_id.to_def_id()); diff --git a/src/librustc_metadata/rmeta/mod.rs b/src/librustc_metadata/rmeta/mod.rs index 669307612055a..64d2961c13765 100644 --- a/src/librustc_metadata/rmeta/mod.rs +++ b/src/librustc_metadata/rmeta/mod.rs @@ -20,7 +20,7 @@ use rustc_session::config::SymbolManglingVersion; use rustc_session::CrateDisambiguator; use rustc_span::edition::Edition; use rustc_span::symbol::Symbol; -use rustc_span::{self, Span}; +use rustc_span::{self, Span, SpanId}; use rustc_target::spec::{PanicStrategy, TargetTriple}; use std::marker::PhantomData; @@ -273,7 +273,7 @@ define_tables! { // as it's an `enum` for which we want to derive (de)serialization, // so the `ty::codec` APIs handle the whole `&'tcx [...]` at once. // Also, as an optimization, a missing entry indicates an empty `&[]`. - inferred_outlives: Table, Span)])>, + inferred_outlives: Table, SpanId)])>, super_predicates: Table)>, mir: Table)>, promoted_mir: Table>)>, diff --git a/src/librustc_middle/lint.rs b/src/librustc_middle/lint.rs index 27239b4ad2e78..0e3c0f10dda88 100644 --- a/src/librustc_middle/lint.rs +++ b/src/librustc_middle/lint.rs @@ -8,8 +8,8 @@ use rustc_hir::HirId; use rustc_session::lint::{builtin, Level, Lint, LintId}; use rustc_session::{DiagnosticMessageId, Session}; use rustc_span::hygiene::MacroKind; -use rustc_span::source_map::{DesugaringKind, ExpnKind, MultiSpan}; -use rustc_span::{Span, Symbol}; +use rustc_span::source_map::{DesugaringKind, ExpnKind, MultiSpanId}; +use rustc_span::{Span, SpanId, Symbol}; /// How a lint level was set. #[derive(Clone, Copy, PartialEq, Eq, HashStable)] @@ -194,7 +194,7 @@ pub fn struct_lint_level<'s, 'd>( lint: &'static Lint, level: Level, src: LintSource, - span: Option, + span: Option, decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>) + 'd, ) { // Avoid codegen bloat from monomorphization by immediately doing dyn dispatch of `decorate` to @@ -204,7 +204,7 @@ pub fn struct_lint_level<'s, 'd>( lint: &'static Lint, level: Level, src: LintSource, - span: Option, + span: Option, decorate: Box FnOnce(LintDiagnosticBuilder<'b>) + 'd>, ) { let mut err = match (level, span) { @@ -336,7 +336,11 @@ pub fn struct_lint_level<'s, 'd>( /// /// This is used to test whether a lint should not even begin to figure out whether it should /// be reported on the current node. -pub fn in_external_macro(sess: &Session, span: Span) -> bool { +pub fn in_external_macro(sess: &Session, span: SpanId) -> bool { + let span = match span { + SpanId::Span(span) => span, + SpanId::DefId(def_id) => crate::ty::tls::with(|tcx| tcx.real_def_span(def_id)), + }; let expn_data = span.ctxt().outer_expn_data(); match expn_data.kind { ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => false, diff --git a/src/librustc_middle/middle/stability.rs b/src/librustc_middle/middle/stability.rs index 54c05bca3bd2b..c3029e0bcf354 100644 --- a/src/librustc_middle/middle/stability.rs +++ b/src/librustc_middle/middle/stability.rs @@ -110,7 +110,7 @@ pub fn report_unstable( let span_key = msp.primary_span().and_then(|sp: Span| { if !sp.is_dummy() { let file = sm.lookup_char_pos(sp.lo()).file; - if file.is_imported() { None } else { Some(span) } + if file.is_imported() { None } else { Some(span.into()) } } else { None } diff --git a/src/librustc_middle/mir/interpret/error.rs b/src/librustc_middle/mir/interpret/error.rs index 06fe3793b2383..28bccc8ff21be 100644 --- a/src/librustc_middle/mir/interpret/error.rs +++ b/src/librustc_middle/mir/interpret/error.rs @@ -11,7 +11,7 @@ use rustc_hir as hir; use rustc_hir::definitions::DefPathData; use rustc_macros::HashStable; use rustc_session::CtfeBacktrace; -use rustc_span::{def_id::DefId, Pos, Span}; +use rustc_span::{def_id::DefId, Pos, SpanId}; use rustc_target::abi::{Align, Size}; use std::{any::Any, backtrace::Backtrace, fmt, mem}; @@ -36,7 +36,7 @@ pub type ConstEvalResult<'tcx> = Result, ErrorHandled>; #[derive(Debug)] pub struct ConstEvalErr<'tcx> { - pub span: Span, + pub span: SpanId, pub error: crate::mir::interpret::InterpError<'tcx>, pub stacktrace: Vec>, } @@ -44,7 +44,7 @@ pub struct ConstEvalErr<'tcx> { #[derive(Debug)] pub struct FrameInfo<'tcx> { pub instance: ty::Instance<'tcx>, - pub span: Span, + pub span: SpanId, pub lint_root: Option, } @@ -59,7 +59,8 @@ impl<'tcx> fmt::Display for FrameInfo<'tcx> { write!(f, "inside `{}`", self.instance)?; } if !self.span.is_dummy() { - let lo = tcx.sess.source_map().lookup_char_pos(self.span.lo()); + let span = tcx.reify_span(self.span); + let lo = tcx.sess.source_map().lookup_char_pos(span.lo()); write!(f, " at {}:{}:{}", lo.file.name, lo.line, lo.col.to_usize() + 1)?; } Ok(()) @@ -86,7 +87,7 @@ impl<'tcx> ConstEvalErr<'tcx> { tcx: TyCtxtAt<'tcx>, message: &str, lint_root: hir::HirId, - span: Option, + span: Option>, ) -> ErrorHandled { self.struct_generic( tcx, @@ -94,6 +95,7 @@ impl<'tcx> ConstEvalErr<'tcx> { |mut lint: DiagnosticBuilder<'_>| { // Apply the span. if let Some(span) = span { + let span = span.into(); let primary_spans = lint.span.primary_spans().to_vec(); // point at the actual error as the primary span lint.replace_span_with(span); diff --git a/src/librustc_middle/mir/interpret/queries.rs b/src/librustc_middle/mir/interpret/queries.rs index a7953f0f900fb..7e48fee2eabf0 100644 --- a/src/librustc_middle/mir/interpret/queries.rs +++ b/src/librustc_middle/mir/interpret/queries.rs @@ -4,7 +4,7 @@ use crate::mir; use crate::ty::subst::{InternalSubsts, SubstsRef}; use crate::ty::{self, TyCtxt}; use rustc_hir::def_id::DefId; -use rustc_span::Span; +use rustc_span::SpanId; impl<'tcx> TyCtxt<'tcx> { /// Evaluates a constant without providing any substitutions. This is useful to evaluate consts @@ -37,7 +37,7 @@ impl<'tcx> TyCtxt<'tcx> { def_id: DefId, substs: SubstsRef<'tcx>, promoted: Option, - span: Option, + span: Option, ) -> ConstEvalResult<'tcx> { match ty::Instance::resolve(self, param_env, def_id, substs) { Ok(Some(instance)) => { @@ -53,7 +53,7 @@ impl<'tcx> TyCtxt<'tcx> { self, param_env: ty::ParamEnv<'tcx>, instance: ty::Instance<'tcx>, - span: Option, + span: Option, ) -> ConstEvalResult<'tcx> { self.const_eval_global_id(param_env, GlobalId { instance, promoted: None }, span) } @@ -63,7 +63,7 @@ impl<'tcx> TyCtxt<'tcx> { self, param_env: ty::ParamEnv<'tcx>, cid: GlobalId<'tcx>, - span: Option, + span: Option, ) -> ConstEvalResult<'tcx> { // Const-eval shouldn't depend on lifetimes at all, so we can erase them, which should // improve caching of queries. diff --git a/src/librustc_middle/mir/mod.rs b/src/librustc_middle/mir/mod.rs index 62e6e1249818a..36b551778c82a 100644 --- a/src/librustc_middle/mir/mod.rs +++ b/src/librustc_middle/mir/mod.rs @@ -27,7 +27,7 @@ use rustc_index::vec::{Idx, IndexVec}; use rustc_macros::HashStable; use rustc_serialize::{Decodable, Encodable}; use rustc_span::symbol::Symbol; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{SpanId, DUMMY_SPID}; use std::borrow::Cow; use std::fmt::{self, Debug, Display, Formatter, Write}; use std::ops::{Index, IndexMut}; @@ -148,10 +148,10 @@ pub struct Body<'tcx> { /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };` /// /// List of places where control flow was destroyed. Used for error reporting. - pub control_flow_destroyed: Vec<(Span, String)>, + pub control_flow_destroyed: Vec<(SpanId, String)>, /// A span representing this MIR, for error reporting. - pub span: Span, + pub span: SpanId, /// Constants that are required to evaluate successfully for this MIR to be well-formed. /// We hold in this field all the constants we are not able to evaluate yet. @@ -178,8 +178,8 @@ impl<'tcx> Body<'tcx> { user_type_annotations: CanonicalUserTypeAnnotations<'tcx>, arg_count: usize, var_debug_info: Vec>, - span: Span, - control_flow_destroyed: Vec<(Span, String)>, + span: SpanId, + control_flow_destroyed: Vec<(SpanId, String)>, generator_kind: Option, ) -> Self { // We need `arg_count` locals, and one for the return place. @@ -228,7 +228,7 @@ impl<'tcx> Body<'tcx> { user_type_annotations: IndexVec::new(), arg_count: 0, spread_arg: None, - span: DUMMY_SP, + span: DUMMY_SPID, required_consts: Vec::new(), control_flow_destroyed: Vec::new(), generator_kind: None, @@ -466,7 +466,7 @@ impl rustc_serialize::UseSpecializedDecodable for ClearCrossCrate< #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)] pub struct SourceInfo { /// The source span for the AST pertaining to this MIR entity. - pub span: Span, + pub span: SpanId, /// The source scope, keeping track of which bindings can be /// seen by debuginfo, active lint levels, `unsafe {...}`, etc. @@ -475,7 +475,7 @@ pub struct SourceInfo { impl SourceInfo { #[inline] - pub fn outermost(span: Span) -> Self { + pub fn outermost(span: SpanId) -> Self { SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE } } } @@ -599,21 +599,21 @@ pub struct VarBindingForm<'tcx> { /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`? pub binding_mode: ty::BindingMode, /// If an explicit type was provided for this variable binding, - /// this holds the source Span of that type. + /// this holds the source SpanId of that type. /// /// NOTE: if you want to change this to a `HirId`, be wary that /// doing so breaks incremental compilation (as of this writing), - /// while a `Span` does not cause our tests to fail. - pub opt_ty_info: Option, + /// while a `SpanId` does not cause our tests to fail. + pub opt_ty_info: Option, /// Place of the RHS of the =, or the subject of the `match` where this /// variable is initialized. None in the case of `let PATTERN;`. /// Some((None, ..)) in the case of and `let [mut] x = ...` because /// (a) the right-hand side isn't evaluated as a place expression. /// (b) it gives a way to separate this case from the remaining cases /// for diagnostics. - pub opt_match_place: Option<(Option>, Span)>, + pub opt_match_place: Option<(Option>, SpanId)>, /// The span of the pattern in which this variable was bound. - pub pat_span: Span, + pub pat_span: SpanId, } #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] @@ -679,8 +679,8 @@ pub struct BlockTailInfo { /// but not e.g., `let _x = { ...; tail };` pub tail_result_is_ignored: bool, - /// `Span` of the tail expression. - pub span: Span, + /// `SpanId` of the tail expression. + pub span: SpanId, } /// A MIR local. @@ -817,7 +817,7 @@ pub struct LocalDecl<'tcx> { // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(target_arch = "x86_64")] -static_assert_size!(LocalDecl<'_>, 56); +static_assert_size!(LocalDecl<'_>, 64); /// Extra information about a some locals that's used for diagnostics. (Not /// used for non-StaticRef temporaries, the return place, or anonymous function @@ -917,17 +917,17 @@ impl<'tcx> LocalDecl<'tcx> { /// Returns `true` is the local is from a compiler desugaring, e.g., /// `__next` from a `for` loop. #[inline] - pub fn from_compiler_desugaring(&self) -> bool { - self.source_info.span.desugaring_kind().is_some() + pub fn from_compiler_desugaring(&self, tcx: TyCtxt<'_>) -> bool { + tcx.reify_span(self.source_info.span).desugaring_kind().is_some() } /// Creates a new `LocalDecl` for a temporary: mutable, non-internal. #[inline] - pub fn new(ty: Ty<'tcx>, span: Span) -> Self { + pub fn new(ty: Ty<'tcx>, span: SpanId) -> Self { Self::with_source_info(ty, SourceInfo::outermost(span)) } - /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`. + /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `SpanId`. #[inline] pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self { LocalDecl { @@ -1402,7 +1402,7 @@ impl<'tcx> BasicBlockData<'tcx> { let mut gap = self.statements.len()..self.statements.len() + extra_stmts; self.statements.resize( gap.end, - Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop }, + Statement { source_info: SourceInfo::outermost(DUMMY_SPID), kind: StatementKind::Nop }, ); for (splice_start, new_stmts) in splices.into_iter().rev() { let splice_end = splice_start + new_stmts.size_hint().0; @@ -1731,7 +1731,7 @@ pub enum FakeReadCause { pub struct LlvmInlineAsm<'tcx> { pub asm: hir::LlvmInlineAsmInner, pub outputs: Box<[Place<'tcx>]>, - pub inputs: Box<[(Span, Operand<'tcx>)]>, + pub inputs: Box<[(SpanId, Operand<'tcx>)]>, } impl Debug for Statement<'_> { @@ -2012,7 +2012,7 @@ rustc_index::newtype_index! { #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct SourceScopeData { - pub span: Span, + pub span: SpanId, pub parent_scope: Option, /// Crate-local information for this source scope, that can't (and @@ -2071,7 +2071,7 @@ impl<'tcx> Operand<'tcx> { tcx: TyCtxt<'tcx>, def_id: DefId, substs: SubstsRef<'tcx>, - span: Span, + span: SpanId, ) -> Self { let ty = tcx.type_of(def_id).subst(tcx, substs); Operand::Constant(box Constant { @@ -2388,7 +2388,7 @@ impl<'tcx> Debug for Rvalue<'tcx> { #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, HashStable)] pub struct Constant<'tcx> { - pub span: Span, + pub span: SpanId, /// Optional user-given type: for something like /// `collect::>`, this would be present and would @@ -2446,7 +2446,7 @@ impl Constant<'tcx> { /// &'static str`. #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)] pub struct UserTypeProjections { - pub contents: Vec<(UserTypeProjection, Span)>, + pub contents: Vec<(UserTypeProjection, SpanId)>, } impl<'tcx> UserTypeProjections { @@ -2458,13 +2458,13 @@ impl<'tcx> UserTypeProjections { self.contents.is_empty() } - pub fn from_projections(projs: impl Iterator) -> Self { + pub fn from_projections(projs: impl Iterator) -> Self { UserTypeProjections { contents: projs.collect() } } pub fn projections_and_spans( &self, - ) -> impl Iterator + ExactSizeIterator { + ) -> impl Iterator + ExactSizeIterator { self.contents.iter() } @@ -2472,7 +2472,7 @@ impl<'tcx> UserTypeProjections { self.contents.iter().map(|&(ref user_type, _span)| user_type) } - pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self { + pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: SpanId) -> Self { self.contents.push((user_ty.clone(), span)); self } diff --git a/src/librustc_middle/mir/mono.rs b/src/librustc_middle/mir/mono.rs index 632607e335626..474d1859b036f 100644 --- a/src/librustc_middle/mir/mono.rs +++ b/src/librustc_middle/mir/mono.rs @@ -10,7 +10,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; use rustc_hir::HirId; use rustc_session::config::OptLevel; -use rustc_span::source_map::Span; +use rustc_span::source_map::SpanId; use rustc_span::symbol::Symbol; use std::fmt; use std::hash::Hash; @@ -195,7 +195,7 @@ impl<'tcx> MonoItem<'tcx> { } } - pub fn local_span(&self, tcx: TyCtxt<'tcx>) -> Option { + pub fn local_span(&self, tcx: TyCtxt<'tcx>) -> Option { match *self { MonoItem::Fn(Instance { def, .. }) => { def.def_id().as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id)) @@ -205,7 +205,7 @@ impl<'tcx> MonoItem<'tcx> { } MonoItem::GlobalAsm(hir_id) => Some(hir_id), } - .map(|hir_id| tcx.hir().span(hir_id)) + .map(|hir_id| tcx.hir().span(hir_id).into()) } } diff --git a/src/librustc_middle/mir/query.rs b/src/librustc_middle/mir/query.rs index 63b8d8c8da782..aef06a65f2fc0 100644 --- a/src/librustc_middle/mir/query.rs +++ b/src/librustc_middle/mir/query.rs @@ -7,7 +7,7 @@ use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_index::bit_set::BitMatrix; use rustc_index::vec::IndexVec; -use rustc_span::{Span, Symbol}; +use rustc_span::{SpanId, Symbol}; use rustc_target::abi::VariantIdx; use smallvec::SmallVec; @@ -157,7 +157,7 @@ pub struct ClosureOutlivesRequirement<'tcx> { pub outlived_free_region: ty::RegionVid, // If not, report an error here ... - pub blame_span: Span, + pub blame_span: SpanId, // ... due to this reason. pub category: ConstraintCategory, diff --git a/src/librustc_middle/mir/visit.rs b/src/librustc_middle/mir/visit.rs index 1f097f24942de..aa19eb82ae106 100644 --- a/src/librustc_middle/mir/visit.rs +++ b/src/librustc_middle/mir/visit.rs @@ -1,7 +1,7 @@ use crate::mir::*; use crate::ty::subst::SubstsRef; use crate::ty::{CanonicalUserTypeAnnotation, Ty}; -use rustc_span::Span; +use rustc_span::SpanId; // # The MIR Visitor // @@ -163,7 +163,7 @@ macro_rules! make_mir_visitor { } fn visit_span(&mut self, - span: & $($mutability)? Span) { + span: & $($mutability)? SpanId) { self.super_span(span); } @@ -774,7 +774,7 @@ macro_rules! make_mir_visitor { self.visit_const(literal, location); } - fn super_span(&mut self, _span: & $($mutability)? Span) { + fn super_span(&mut self, _span: & $($mutability)? SpanId) { } fn super_source_info(&mut self, source_info: & $($mutability)? SourceInfo) { @@ -798,8 +798,8 @@ macro_rules! make_mir_visitor { _index: UserTypeAnnotationIndex, ty: & $($mutability)? CanonicalUserTypeAnnotation<'tcx>, ) { - self.visit_span(& $($mutability)? ty.span); - self.visit_ty(& $($mutability)? ty.inferred_ty, TyContext::UserTy(ty.span)); + self.visit_span(& $($mutability)? ty.span.into()); + self.visit_ty(& $($mutability)? ty.inferred_ty, TyContext::UserTy(ty.span.into())); } fn super_ty(&mut self, _ty: $(& $mutability)? Ty<'tcx>) { @@ -1024,7 +1024,7 @@ pub enum TyContext { }, /// The inferred type of a user type annotation. - UserTy(Span), + UserTy(SpanId), /// The return type of the function. ReturnTy(SourceInfo), diff --git a/src/librustc_middle/query/mod.rs b/src/librustc_middle/query/mod.rs index 2ceba51949420..6266a209f686e 100644 --- a/src/librustc_middle/query/mod.rs +++ b/src/librustc_middle/query/mod.rs @@ -245,7 +245,7 @@ rustc_queries! { /// Returns the inferred outlives predicates (e.g., for `struct /// Foo<'a, T> { x: &'a T }`, this would return `T: 'a`). - query inferred_outlives_of(_: DefId) -> &'tcx [(ty::Predicate<'tcx>, Span)] {} + query inferred_outlives_of(_: DefId) -> &'tcx [(ty::Predicate<'tcx>, SpanId)] {} /// Maps from the `DefId` of a trait to the list of /// super-predicates. This is a subset of the full list of @@ -618,7 +618,7 @@ rustc_queries! { } query def_kind(_: DefId) -> DefKind {} - query def_span(_: DefId) -> Span { + query real_def_span(_: DefId) -> Span { // FIXME(mw): DefSpans are not really inputs since they are derived from // HIR. But at the moment HIR hashing still contains some hacks that allow // to make type debuginfo to be source location independent. Declaring @@ -1048,7 +1048,7 @@ rustc_queries! { desc { |tcx| "maybe_unused_trait_import for `{}`", tcx.def_path_str(def_id.to_def_id()) } } query maybe_unused_extern_crates(_: CrateNum) - -> &'tcx [(DefId, Span)] { + -> &'tcx [(DefId, SpanId)] { eval_always desc { "looking up all possibly unused extern crates" } } diff --git a/src/librustc_middle/traits/mod.rs b/src/librustc_middle/traits/mod.rs index 1254174a7a5f9..1ad3b12fef210 100644 --- a/src/librustc_middle/traits/mod.rs +++ b/src/librustc_middle/traits/mod.rs @@ -16,7 +16,7 @@ use crate::ty::{self, AdtKind, Ty, TyCtxt}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_span::symbol::Symbol; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{Span, SpanId, DUMMY_SP, DUMMY_SPID}; use smallvec::SmallVec; use std::borrow::Cow; @@ -568,17 +568,17 @@ pub struct VtableTraitAliasData<'tcx, N> { #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)] pub enum ObjectSafetyViolation { /// `Self: Sized` declared on the trait. - SizedSelf(SmallVec<[Span; 1]>), + SizedSelf(SmallVec<[SpanId; 1]>), /// Supertrait reference references `Self` an in illegal location /// (e.g., `trait Foo : Bar`). - SupertraitSelf(SmallVec<[Span; 1]>), + SupertraitSelf(SmallVec<[SpanId; 1]>), /// Method has something illegal. - Method(Symbol, MethodViolationCode, Span), + Method(Symbol, MethodViolationCode, SpanId), /// Associated const. - AssocConst(Symbol, Span), + AssocConst(Symbol, SpanId), } impl ObjectSafetyViolation { @@ -586,7 +586,7 @@ impl ObjectSafetyViolation { match *self { ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(), ObjectSafetyViolation::SupertraitSelf(ref spans) => { - if spans.iter().any(|sp| *sp != DUMMY_SP) { + if spans.iter().any(|sp| *sp != DUMMY_SPID) { "it uses `Self` as a type parameter in this".into() } else { "it cannot use `Self` as a type parameter in a supertrait or `where`-clause" @@ -599,7 +599,7 @@ impl ObjectSafetyViolation { ObjectSafetyViolation::Method( name, MethodViolationCode::ReferencesSelfInput(_), - DUMMY_SP, + DUMMY_SPID, ) => format!("method `{}` references the `Self` type in its parameters", name).into(), ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => { format!("method `{}` references the `Self` type in this parameter", name).into() @@ -620,14 +620,14 @@ impl ObjectSafetyViolation { ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => { format!("method `{}`'s `self` parameter cannot be dispatched on", name).into() } - ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => { + ObjectSafetyViolation::AssocConst(name, DUMMY_SPID) => { format!("it contains associated `const` `{}`", name).into() } ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(), } } - pub fn solution(&self) -> Option<(String, Option<(String, Span)>)> { + pub fn solution(&self) -> Option<(String, Option<(String, SpanId)>)> { Some(match *self { ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => { return None; @@ -655,15 +655,15 @@ impl ObjectSafetyViolation { }) } - pub fn spans(&self) -> SmallVec<[Span; 1]> { - // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so + pub fn spans(&self) -> SmallVec<[SpanId; 1]> { + // When `span` comes from a separate crate, it'll be `DUMMY_SPID`. Treat it as `None` so // diagnostics use a `note` instead of a `span_label`. match self { ObjectSafetyViolation::SupertraitSelf(spans) | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(), ObjectSafetyViolation::AssocConst(_, span) | ObjectSafetyViolation::Method(_, _, span) - if *span != DUMMY_SP => + if *span != DUMMY_SPID => { smallvec![*span] } @@ -676,7 +676,7 @@ impl ObjectSafetyViolation { #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)] pub enum MethodViolationCode { /// e.g., `fn foo()` - StaticMethod(Option<(&'static str, Span)>), + StaticMethod(Option<(&'static str, SpanId)>), /// e.g., `fn foo(&self, x: Self)` ReferencesSelfInput(usize), diff --git a/src/librustc_middle/ty/codec.rs b/src/librustc_middle/ty/codec.rs index cbbc937ed7d31..d9bf2f4005895 100644 --- a/src/librustc_middle/ty/codec.rs +++ b/src/librustc_middle/ty/codec.rs @@ -14,7 +14,7 @@ use crate::ty::{self, List, Ty, TyCtxt}; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::{CrateNum, DefId}; use rustc_serialize::{opaque, Decodable, Decoder, Encodable, Encoder}; -use rustc_span::Span; +use rustc_span::SpanId; use std::hash::Hash; use std::intrinsics; @@ -93,7 +93,7 @@ where pub fn encode_spanned_predicates<'tcx, E, C>( encoder: &mut E, - predicates: &'tcx [(ty::Predicate<'tcx>, Span)], + predicates: &'tcx [(ty::Predicate<'tcx>, SpanId)], cache: C, ) -> Result<(), E::Error> where @@ -187,7 +187,7 @@ where #[inline] pub fn decode_spanned_predicates( decoder: &mut D, -) -> Result<&'tcx [(ty::Predicate<'tcx>, Span)], D::Error> +) -> Result<&'tcx [(ty::Predicate<'tcx>, SpanId)], D::Error> where D: TyDecoder<'tcx>, { @@ -356,7 +356,7 @@ macro_rules! implement_ty_decoder { use $crate::ty::subst::SubstsRef; use rustc_hir::def_id::{CrateNum}; - use rustc_span::Span; + use rustc_span::SpanId; use super::$DecoderName; @@ -413,10 +413,10 @@ macro_rules! implement_ty_decoder { } } - impl<$($typaram),*> SpecializedDecoder<&'tcx [(ty::Predicate<'tcx>, Span)]> + impl<$($typaram),*> SpecializedDecoder<&'tcx [(ty::Predicate<'tcx>, SpanId)]> for $DecoderName<$($typaram),*> { fn specialized_decode(&mut self) - -> Result<&'tcx [(ty::Predicate<'tcx>, Span)], Self::Error> { + -> Result<&'tcx [(ty::Predicate<'tcx>, SpanId)], Self::Error> { decode_spanned_predicates(self) } } diff --git a/src/librustc_middle/ty/context.rs b/src/librustc_middle/ty/context.rs index 86b740b8503b8..db0593a8ca7ea 100644 --- a/src/librustc_middle/ty/context.rs +++ b/src/librustc_middle/ty/context.rs @@ -57,9 +57,9 @@ use rustc_macros::HashStable; use rustc_session::config::{BorrowckMode, CrateType, OutputFilenames}; use rustc_session::lint::{Level, Lint}; use rustc_session::Session; -use rustc_span::source_map::MultiSpan; +use rustc_span::source_map::MultiSpanId; use rustc_span::symbol::{kw, sym, Symbol}; -use rustc_span::Span; +use rustc_span::{Span, SpanId}; use rustc_target::abi::{Layout, TargetDataLayout, VariantIdx}; use rustc_target::spec::abi; @@ -942,7 +942,7 @@ pub struct GlobalCtxt<'tcx> { pub queries: query::Queries<'tcx>, maybe_unused_trait_imports: FxHashSet, - maybe_unused_extern_crates: Vec<(DefId, Span)>, + maybe_unused_extern_crates: Vec<(DefId, SpanId)>, /// A map of glob use to a set of names it actually imports. Currently only /// used in save-analysis. glob_map: FxHashMap>, @@ -1158,7 +1158,7 @@ impl<'tcx> TyCtxt<'tcx> { maybe_unused_extern_crates: resolutions .maybe_unused_extern_crates .into_iter() - .map(|(id, sp)| (definitions.local_def_id(id).to_def_id(), sp)) + .map(|(id, sp)| (definitions.local_def_id(id).to_def_id(), sp.into())) .collect(), glob_map: resolutions .glob_map @@ -1225,6 +1225,17 @@ impl<'tcx> TyCtxt<'tcx> { self.features_query(LOCAL_CRATE) } + pub fn def_span(self, id: impl ty::query::IntoQueryParam) -> SpanId { + SpanId::DefId(id.into_query_param()) + } + + pub fn reify_span(self, sp: SpanId) -> Span { + match sp { + SpanId::Span(sp) => sp, + SpanId::DefId(id) => self.real_def_span(id), + } + } + pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey { if let Some(id) = id.as_local() { self.hir().def_key(id) } else { self.cstore.def_key(id) } } @@ -2562,7 +2573,7 @@ impl<'tcx> TyCtxt<'tcx> { self, lint: &'static Lint, hir_id: HirId, - span: impl Into, + span: impl Into, decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), ) { let (level, src) = self.lint_level_at_node(lint, hir_id); diff --git a/src/librustc_middle/ty/error.rs b/src/librustc_middle/ty/error.rs index f3b6a53dfeb82..4ab95b8d1c759 100644 --- a/src/librustc_middle/ty/error.rs +++ b/src/librustc_middle/ty/error.rs @@ -381,11 +381,11 @@ impl<'tcx> TyCtxt<'tcx> { } (ty::Param(expected), ty::Param(found)) => { let generics = self.generics_of(body_owner_def_id); - let e_span = self.def_span(generics.type_param(expected, self).def_id); + let e_span = self.real_def_span(generics.type_param(expected, self).def_id); if !sp.contains(e_span) { db.span_label(e_span, "expected type parameter"); } - let f_span = self.def_span(generics.type_param(found, self).def_id); + let f_span = self.real_def_span(generics.type_param(found, self).def_id); if !sp.contains(f_span) { db.span_label(f_span, "found type parameter"); } @@ -404,7 +404,7 @@ impl<'tcx> TyCtxt<'tcx> { } (ty::Param(p), ty::Projection(proj)) | (ty::Projection(proj), ty::Param(p)) => { let generics = self.generics_of(body_owner_def_id); - let p_span = self.def_span(generics.type_param(p, self).def_id); + let p_span = self.real_def_span(generics.type_param(p, self).def_id); if !sp.contains(p_span) { db.span_label(p_span, "this type parameter"); } @@ -446,7 +446,7 @@ impl<'tcx> TyCtxt<'tcx> { (ty::Param(p), ty::Dynamic(..) | ty::Opaque(..)) | (ty::Dynamic(..) | ty::Opaque(..), ty::Param(p)) => { let generics = self.generics_of(body_owner_def_id); - let p_span = self.def_span(generics.type_param(p, self).def_id); + let p_span = self.real_def_span(generics.type_param(p, self).def_id); if !sp.contains(p_span) { db.span_label(p_span, "this type parameter"); } @@ -486,7 +486,7 @@ impl Trait for X { } (ty::Param(p), _) | (_, ty::Param(p)) => { let generics = self.generics_of(body_owner_def_id); - let p_span = self.def_span(generics.type_param(p, self).def_id); + let p_span = self.real_def_span(generics.type_param(p, self).def_id); if !sp.contains(p_span) { db.span_label(p_span, "this type parameter"); } @@ -696,7 +696,7 @@ impl Trait for X { // a return type. This can occur when dealing with `TryStream` (#71035). if self.constrain_associated_type_structured_suggestion( db, - self.def_span(def_id), + self.real_def_span(def_id), &assoc, values.found, &msg, @@ -766,7 +766,7 @@ fn foo(&self) -> Self::T { String::new() } if item_def_id == proj_ty_item_def_id => { Some(( - self.sess.source_map().guess_head_span(self.def_span(item.def_id)), + self.sess.source_map().guess_head_span(self.real_def_span(item.def_id)), format!("consider calling `{}`", self.def_path_str(item.def_id)), )) } diff --git a/src/librustc_middle/ty/layout.rs b/src/librustc_middle/ty/layout.rs index 7c4e4d095bc5d..4d36c59570c6c 100644 --- a/src/librustc_middle/ty/layout.rs +++ b/src/librustc_middle/ty/layout.rs @@ -12,7 +12,7 @@ use rustc_index::bit_set::BitSet; use rustc_index::vec::{Idx, IndexVec}; use rustc_session::{DataTypeKind, FieldInfo, SizeKind, VariantInfo}; use rustc_span::symbol::{Ident, Symbol}; -use rustc_span::DUMMY_SP; +use rustc_span::DUMMY_SPID; use rustc_target::abi::call::{ ArgAbi, ArgAttribute, ArgAttributes, Conv, FnAbi, PassMode, Reg, RegKind, }; @@ -535,7 +535,7 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { } let pointee = tcx.normalize_erasing_regions(param_env, pointee); - if pointee.is_sized(tcx.at(DUMMY_SP), param_env) { + if pointee.is_sized(tcx.at(DUMMY_SPID), param_env) { return Ok(tcx.intern_layout(Layout::scalar(self, data_ptr))); } @@ -798,7 +798,7 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { let param_env = tcx.param_env(def.did); let last_field = def.variants[v].fields.last().unwrap(); let always_sized = - tcx.type_of(last_field.did).is_sized(tcx.at(DUMMY_SP), param_env); + tcx.type_of(last_field.did).is_sized(tcx.at(DUMMY_SPID), param_env); if !always_sized { StructKind::MaybeUnsized } else { @@ -2160,7 +2160,7 @@ where ty::Ref(_, ty, mt) if offset.bytes() == 0 => { let tcx = cx.tcx(); - let is_freeze = ty.is_freeze(tcx, cx.param_env(), DUMMY_SP); + let is_freeze = ty.is_freeze(tcx, cx.param_env(), DUMMY_SPID); let kind = match mt { hir::Mutability::Not => { if is_freeze { diff --git a/src/librustc_middle/ty/mod.rs b/src/librustc_middle/ty/mod.rs index 571e50f5ae26b..d39da0eaeda56 100644 --- a/src/librustc_middle/ty/mod.rs +++ b/src/librustc_middle/ty/mod.rs @@ -39,7 +39,7 @@ use rustc_serialize::{self, Encodable, Encoder}; use rustc_session::DataTypeKind; use rustc_span::hygiene::ExpnId; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::Span; +use rustc_span::{Span, SpanId}; use rustc_target::abi::{Align, VariantIdx}; use std::cell::RefCell; @@ -1082,7 +1082,7 @@ impl<'tcx> Generics { #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct GenericPredicates<'tcx> { pub parent: Option, - pub predicates: &'tcx [(Predicate<'tcx>, Span)], + pub predicates: &'tcx [(Predicate<'tcx>, SpanId)], } impl<'tcx> GenericPredicates<'tcx> { @@ -1206,7 +1206,7 @@ pub struct CratePredicatesMap<'tcx> { /// For each struct with outlive bounds, maps to a vector of the /// predicate of its outlive bounds. If an item has no outlives /// bounds, it will have no entry. - pub predicates: FxHashMap, Span)]>, + pub predicates: FxHashMap, SpanId)]>, } impl<'tcx> AsRef> for Predicate<'tcx> { @@ -1529,7 +1529,7 @@ impl<'tcx> Predicate<'tcx> { #[derive(Clone, Debug, TypeFoldable)] pub struct InstantiatedPredicates<'tcx> { pub predicates: Vec>, - pub spans: Vec, + pub spans: Vec, } impl<'tcx> InstantiatedPredicates<'tcx> { diff --git a/src/librustc_middle/ty/print/pretty.rs b/src/librustc_middle/ty/print/pretty.rs index cf34fa53a1bed..a411c82762529 100644 --- a/src/librustc_middle/ty/print/pretty.rs +++ b/src/librustc_middle/ty/print/pretty.rs @@ -895,7 +895,7 @@ pub trait PrettyPrinter<'tcx>: } _ => { if did.is_local() { - let span = self.tcx().def_span(did); + let span = self.tcx().real_def_span(did); if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) { p!(write("{}", snip)) @@ -1347,7 +1347,7 @@ impl Printer<'tcx> for FmtPrinter<'_, 'tcx, F> { // pretty printing some span information. This should // only occur very early in the compiler pipeline. let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id }; - let span = self.tcx.def_span(def_id); + let span = self.tcx.real_def_span(def_id); self = self.print_def_path(parent_def_id, &[])?; diff --git a/src/librustc_middle/ty/query/keys.rs b/src/librustc_middle/ty/query/keys.rs index 239691dbd17ac..4912ac68f5e28 100644 --- a/src/librustc_middle/ty/query/keys.rs +++ b/src/librustc_middle/ty/query/keys.rs @@ -8,7 +8,7 @@ use crate::ty::{self, Ty, TyCtxt}; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; use rustc_query_system::query::DefaultCacheSelector; use rustc_span::symbol::Symbol; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{SpanId, DUMMY_SPID}; /// The `Key` trait controls what types can legally be used as the key /// for a query. @@ -21,7 +21,7 @@ pub trait Key { /// In the event that a cycle occurs, if no explicit span has been /// given for a query with key `self`, what span should we use? - fn default_span(&self, tcx: TyCtxt<'_>) -> Span; + fn default_span(&self, tcx: TyCtxt<'_>) -> SpanId; } impl<'tcx> Key for ty::InstanceDef<'tcx> { @@ -31,7 +31,7 @@ impl<'tcx> Key for ty::InstanceDef<'tcx> { LOCAL_CRATE } - fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + fn default_span(&self, tcx: TyCtxt<'_>) -> SpanId { tcx.def_span(self.def_id()) } } @@ -43,7 +43,7 @@ impl<'tcx> Key for ty::Instance<'tcx> { LOCAL_CRATE } - fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + fn default_span(&self, tcx: TyCtxt<'_>) -> SpanId { tcx.def_span(self.def_id()) } } @@ -55,7 +55,7 @@ impl<'tcx> Key for mir::interpret::GlobalId<'tcx> { self.instance.query_crate() } - fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + fn default_span(&self, tcx: TyCtxt<'_>) -> SpanId { self.instance.default_span(tcx) } } @@ -67,8 +67,8 @@ impl<'tcx> Key for mir::interpret::LitToConstInput<'tcx> { LOCAL_CRATE } - fn default_span(&self, _tcx: TyCtxt<'_>) -> Span { - DUMMY_SP + fn default_span(&self, _tcx: TyCtxt<'_>) -> SpanId { + DUMMY_SPID } } @@ -78,8 +78,8 @@ impl Key for CrateNum { fn query_crate(&self) -> CrateNum { *self } - fn default_span(&self, _: TyCtxt<'_>) -> Span { - DUMMY_SP + fn default_span(&self, _: TyCtxt<'_>) -> SpanId { + DUMMY_SPID } } @@ -89,7 +89,7 @@ impl Key for LocalDefId { fn query_crate(&self) -> CrateNum { self.to_def_id().query_crate() } - fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + fn default_span(&self, tcx: TyCtxt<'_>) -> SpanId { self.to_def_id().default_span(tcx) } } @@ -100,7 +100,7 @@ impl Key for DefId { fn query_crate(&self) -> CrateNum { self.krate } - fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + fn default_span(&self, tcx: TyCtxt<'_>) -> SpanId { tcx.def_span(*self) } } @@ -111,7 +111,7 @@ impl Key for (DefId, DefId) { fn query_crate(&self) -> CrateNum { self.0.krate } - fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + fn default_span(&self, tcx: TyCtxt<'_>) -> SpanId { self.1.default_span(tcx) } } @@ -122,7 +122,7 @@ impl Key for (DefId, LocalDefId) { fn query_crate(&self) -> CrateNum { self.0.krate } - fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + fn default_span(&self, tcx: TyCtxt<'_>) -> SpanId { self.1.default_span(tcx) } } @@ -133,7 +133,7 @@ impl Key for (CrateNum, DefId) { fn query_crate(&self) -> CrateNum { self.0 } - fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + fn default_span(&self, tcx: TyCtxt<'_>) -> SpanId { self.1.default_span(tcx) } } @@ -144,7 +144,7 @@ impl Key for (DefId, SimplifiedType) { fn query_crate(&self) -> CrateNum { self.0.krate } - fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + fn default_span(&self, tcx: TyCtxt<'_>) -> SpanId { self.0.default_span(tcx) } } @@ -155,8 +155,8 @@ impl<'tcx> Key for SubstsRef<'tcx> { fn query_crate(&self) -> CrateNum { LOCAL_CRATE } - fn default_span(&self, _: TyCtxt<'_>) -> Span { - DUMMY_SP + fn default_span(&self, _: TyCtxt<'_>) -> SpanId { + DUMMY_SPID } } @@ -166,7 +166,7 @@ impl<'tcx> Key for (DefId, SubstsRef<'tcx>) { fn query_crate(&self) -> CrateNum { self.0.krate } - fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + fn default_span(&self, tcx: TyCtxt<'_>) -> SpanId { self.0.default_span(tcx) } } @@ -177,7 +177,7 @@ impl<'tcx> Key for (ty::ParamEnv<'tcx>, ty::PolyTraitRef<'tcx>) { fn query_crate(&self) -> CrateNum { self.1.def_id().krate } - fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + fn default_span(&self, tcx: TyCtxt<'_>) -> SpanId { tcx.def_span(self.1.def_id()) } } @@ -188,8 +188,8 @@ impl<'tcx> Key for (&'tcx ty::Const<'tcx>, mir::Field) { fn query_crate(&self) -> CrateNum { LOCAL_CRATE } - fn default_span(&self, _: TyCtxt<'_>) -> Span { - DUMMY_SP + fn default_span(&self, _: TyCtxt<'_>) -> SpanId { + DUMMY_SPID } } @@ -199,7 +199,7 @@ impl<'tcx> Key for ty::PolyTraitRef<'tcx> { fn query_crate(&self) -> CrateNum { self.def_id().krate } - fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + fn default_span(&self, tcx: TyCtxt<'_>) -> SpanId { tcx.def_span(self.def_id()) } } @@ -210,8 +210,8 @@ impl<'tcx> Key for GenericArg<'tcx> { fn query_crate(&self) -> CrateNum { LOCAL_CRATE } - fn default_span(&self, _: TyCtxt<'_>) -> Span { - DUMMY_SP + fn default_span(&self, _: TyCtxt<'_>) -> SpanId { + DUMMY_SPID } } @@ -221,8 +221,8 @@ impl<'tcx> Key for &'tcx ty::Const<'tcx> { fn query_crate(&self) -> CrateNum { LOCAL_CRATE } - fn default_span(&self, _: TyCtxt<'_>) -> Span { - DUMMY_SP + fn default_span(&self, _: TyCtxt<'_>) -> SpanId { + DUMMY_SPID } } @@ -232,8 +232,8 @@ impl<'tcx> Key for Ty<'tcx> { fn query_crate(&self) -> CrateNum { LOCAL_CRATE } - fn default_span(&self, _: TyCtxt<'_>) -> Span { - DUMMY_SP + fn default_span(&self, _: TyCtxt<'_>) -> SpanId { + DUMMY_SPID } } @@ -243,8 +243,8 @@ impl<'tcx> Key for ty::ParamEnv<'tcx> { fn query_crate(&self) -> CrateNum { LOCAL_CRATE } - fn default_span(&self, _: TyCtxt<'_>) -> Span { - DUMMY_SP + fn default_span(&self, _: TyCtxt<'_>) -> SpanId { + DUMMY_SPID } } @@ -254,7 +254,7 @@ impl<'tcx, T: Key> Key for ty::ParamEnvAnd<'tcx, T> { fn query_crate(&self) -> CrateNum { self.value.query_crate() } - fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + fn default_span(&self, tcx: TyCtxt<'_>) -> SpanId { self.value.default_span(tcx) } } @@ -265,8 +265,8 @@ impl Key for Symbol { fn query_crate(&self) -> CrateNum { LOCAL_CRATE } - fn default_span(&self, _tcx: TyCtxt<'_>) -> Span { - DUMMY_SP + fn default_span(&self, _tcx: TyCtxt<'_>) -> SpanId { + DUMMY_SPID } } @@ -279,8 +279,8 @@ impl<'tcx, T> Key for Canonical<'tcx, T> { LOCAL_CRATE } - fn default_span(&self, _tcx: TyCtxt<'_>) -> Span { - DUMMY_SP + fn default_span(&self, _tcx: TyCtxt<'_>) -> SpanId { + DUMMY_SPID } } @@ -291,7 +291,7 @@ impl Key for (Symbol, u32, u32) { LOCAL_CRATE } - fn default_span(&self, _tcx: TyCtxt<'_>) -> Span { - DUMMY_SP + fn default_span(&self, _tcx: TyCtxt<'_>) -> SpanId { + DUMMY_SPID } } diff --git a/src/librustc_middle/ty/query/mod.rs b/src/librustc_middle/ty/query/mod.rs index e1a5a766ca15a..f76050a56a882 100644 --- a/src/librustc_middle/ty/query/mod.rs +++ b/src/librustc_middle/ty/query/mod.rs @@ -52,7 +52,7 @@ use rustc_target::spec::PanicStrategy; use rustc_ast::ast; use rustc_attr as attr; use rustc_span::symbol::Symbol; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{Span, SpanId, DUMMY_SP, DUMMY_SPID}; use std::borrow::Cow; use std::collections::BTreeMap; use std::ops::Deref; @@ -215,4 +215,4 @@ mod sealed { } } -use sealed::IntoQueryParam; +pub(crate) use sealed::IntoQueryParam; diff --git a/src/librustc_middle/ty/query/on_disk_cache.rs b/src/librustc_middle/ty/query/on_disk_cache.rs index 71c2c24cc0a9f..9bc837898b72c 100644 --- a/src/librustc_middle/ty/query/on_disk_cache.rs +++ b/src/librustc_middle/ty/query/on_disk_cache.rs @@ -21,7 +21,7 @@ use rustc_span::hygiene::{ExpnId, SyntaxContext}; use rustc_span::source_map::{SourceMap, StableSourceFileId}; use rustc_span::symbol::Ident; use rustc_span::CachingSourceMapView; -use rustc_span::{BytePos, SourceFile, Span, DUMMY_SP}; +use rustc_span::{BytePos, SourceFile, Span, SpanId, DUMMY_SP}; use std::mem; const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE; @@ -838,7 +838,7 @@ where } } -impl<'a, 'tcx, E> SpecializedEncoder<&'tcx [(ty::Predicate<'tcx>, Span)]> +impl<'a, 'tcx, E> SpecializedEncoder<&'tcx [(ty::Predicate<'tcx>, SpanId)]> for CacheEncoder<'a, 'tcx, E> where E: 'a + TyEncoder, @@ -846,7 +846,7 @@ where #[inline] fn specialized_encode( &mut self, - predicates: &&'tcx [(ty::Predicate<'tcx>, Span)], + predicates: &&'tcx [(ty::Predicate<'tcx>, SpanId)], ) -> Result<(), Self::Error> { ty_codec::encode_spanned_predicates(self, predicates, |encoder| { &mut encoder.predicate_shorthands diff --git a/src/librustc_middle/ty/query/plumbing.rs b/src/librustc_middle/ty/query/plumbing.rs index c711de9476e9d..c791e6b91e0ff 100644 --- a/src/librustc_middle/ty/query/plumbing.rs +++ b/src/librustc_middle/ty/query/plumbing.rs @@ -12,9 +12,11 @@ use rustc_query_system::query::{CycleError, QueryJobId, QueryJobInfo}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::Lock; use rustc_data_structures::thin_vec::ThinVec; -use rustc_errors::{struct_span_err, Diagnostic, DiagnosticBuilder, Handler, Level}; +use rustc_errors::{ + struct_span_err, Diagnostic, DiagnosticBuilder, Handler, Level, RealDiagnostic, +}; use rustc_span::def_id::DefId; -use rustc_span::Span; +use rustc_span::SpanId; impl QueryContext for TyCtxt<'tcx> { type Query = Query<'tcx>; @@ -84,7 +86,7 @@ impl<'tcx> TyCtxt<'tcx> { ) -> DiagnosticBuilder<'tcx> { assert!(!stack.is_empty()); - let fix_span = |span: Span, query: &Query<'tcx>| { + let fix_span = |span: SpanId, query: &Query<'tcx>| { self.sess.source_map().guess_head_span(query.default_span(self, span)) }; @@ -144,7 +146,7 @@ impl<'tcx> TyCtxt<'tcx> { } else { break; }; - let mut diag = Diagnostic::new( + let mut diag = RealDiagnostic::new( Level::FailureNote, &format!( "#{} [{}] {}", @@ -153,8 +155,8 @@ impl<'tcx> TyCtxt<'tcx> { query_info.info.query.describe(icx.tcx) ), ); - diag.span = - icx.tcx.sess.source_map().guess_head_span(query_info.info.span).into(); + let info_span = icx.tcx.reify_span(query_info.info.span); + diag.span = icx.tcx.sess.source_map().guess_head_span(info_span).into(); handler.force_print_diagnostic(diag); current_query = query_info.job.parent; @@ -294,18 +296,28 @@ macro_rules! define_queries_inner { } // FIXME(eddyb) Get more valid `Span`s on queries. - pub fn default_span(&self, tcx: TyCtxt<$tcx>, span: Span) -> Span { - if !span.is_dummy() { - return span; + pub fn default_span(&self, tcx: TyCtxt<$tcx>, span: SpanId) -> Span { + if let SpanId::Span(span) = span { + if !span.is_dummy() { + return span; + } } + // The `def_span` query is used to calculate `default_span`, // so exit to avoid infinite recursion. - if let Query::def_span(..) = *self { - return span + if let Query::real_def_span(..) = *self { + return DUMMY_SP; } - match *self { - $(Query::$name(key) => key.default_span(tcx),)* + + let span = tcx.reify_span(span); + if !span.is_dummy() { + return span; } + + let spid = match *self { + $(Query::$name(key) => key.default_span(tcx),)* + }; + tcx.reify_span(spid) } } @@ -393,7 +405,7 @@ macro_rules! define_queries_inner { #[derive(Copy, Clone)] pub struct TyCtxtAt<'tcx> { pub tcx: TyCtxt<'tcx>, - pub span: Span, + pub span: SpanId, } impl Deref for TyCtxtAt<'tcx> { @@ -417,10 +429,10 @@ macro_rules! define_queries_inner { /// Returns a transparent wrapper for `TyCtxt` which uses /// `span` as the location of queries performed through it. #[inline(always)] - pub fn at(self, span: Span) -> TyCtxtAt<$tcx> { + pub fn at(self, span: impl Into) -> TyCtxtAt<$tcx> { TyCtxtAt { tcx: self, - span + span: span.into(), } } diff --git a/src/librustc_middle/ty/structural_impls.rs b/src/librustc_middle/ty/structural_impls.rs index c8406a024ecff..2f02b0fadf8c5 100644 --- a/src/librustc_middle/ty/structural_impls.rs +++ b/src/librustc_middle/ty/structural_impls.rs @@ -290,6 +290,7 @@ CloneTypeFoldableAndLiftImpls! { crate::ty::UniverseIndex, crate::ty::Variance, ::rustc_span::Span, + ::rustc_span::SpanId, } /////////////////////////////////////////////////////////////////////////// diff --git a/src/librustc_middle/ty/util.rs b/src/librustc_middle/ty/util.rs index a89927ecfb72c..a0aa000118d48 100644 --- a/src/librustc_middle/ty/util.rs +++ b/src/librustc_middle/ty/util.rs @@ -18,7 +18,7 @@ use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_macros::HashStable; -use rustc_span::Span; +use rustc_span::{Span, SpanId}; use rustc_target::abi::{Integer, Size, TargetDataLayout}; use smallvec::SmallVec; use std::{cmp, fmt}; @@ -683,7 +683,7 @@ impl<'tcx> ty::TyS<'tcx> { &'tcx self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, - span: Span, + span: SpanId, ) -> bool { tcx.at(span).is_copy_raw(param_env.and(self)) } @@ -709,7 +709,7 @@ impl<'tcx> ty::TyS<'tcx> { &'tcx self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, - span: Span, + span: SpanId, ) -> bool { self.is_trivially_freeze() || tcx.at(span).is_freeze_raw(param_env.and(self)) } diff --git a/src/librustc_middle/util/bug.rs b/src/librustc_middle/util/bug.rs index 54cd8a29f9474..ad3d272d5c625 100644 --- a/src/librustc_middle/util/bug.rs +++ b/src/librustc_middle/util/bug.rs @@ -1,7 +1,7 @@ // These functions are used by macro expansion for bug! and span_bug! use crate::ty::{tls, TyCtxt}; -use rustc_span::{MultiSpan, Span}; +use rustc_span::{MultiSpanId, Span}; use std::fmt; #[cold] @@ -14,7 +14,7 @@ pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments<'_>) -> ! { #[cold] #[inline(never)] -pub fn span_bug_fmt>( +pub fn span_bug_fmt>( file: &'static str, line: u32, span: S, @@ -23,7 +23,7 @@ pub fn span_bug_fmt>( opt_span_bug_fmt(file, line, Some(span), args); } -fn opt_span_bug_fmt>( +fn opt_span_bug_fmt>( file: &'static str, line: u32, span: Option, @@ -45,7 +45,7 @@ fn opt_span_bug_fmt>( /// interactions with the query system and incremental. pub fn trigger_delay_span_bug(tcx: TyCtxt<'_>, key: rustc_hir::def_id::DefId) { tcx.sess.delay_span_bug( - tcx.def_span(key), + tcx.real_def_span(key), "delayed span bug triggered by #[rustc_error(delay_span_bug_from_inside_query)]", ); } diff --git a/src/librustc_mir/borrow_check/constraints/graph.rs b/src/librustc_mir/borrow_check/constraints/graph.rs index f3f6b8c10da7c..28dd87921c958 100644 --- a/src/librustc_mir/borrow_check/constraints/graph.rs +++ b/src/librustc_mir/borrow_check/constraints/graph.rs @@ -2,7 +2,7 @@ use rustc_data_structures::graph; use rustc_index::vec::IndexVec; use rustc_middle::mir::ConstraintCategory; use rustc_middle::ty::RegionVid; -use rustc_span::DUMMY_SP; +use rustc_span::DUMMY_SPID; use crate::borrow_check::{ constraints::OutlivesConstraintIndex, @@ -155,7 +155,7 @@ impl<'s, D: ConstraintGraphDirecton> Iterator for Edges<'s, D> { Some(OutlivesConstraint { sup: self.static_region, sub: next_static_idx.into(), - locations: Locations::All(DUMMY_SP), + locations: Locations::All(DUMMY_SPID), category: ConstraintCategory::Internal, }) } else { diff --git a/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs b/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs index 5f1c0911da2bf..7a7f0153e52fe 100644 --- a/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs +++ b/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs @@ -12,7 +12,7 @@ use rustc_middle::mir::{ }; use rustc_middle::ty::{self, suggest_constraining_type_param, Ty}; use rustc_span::source_map::DesugaringKind; -use rustc_span::Span; +use rustc_span::SpanId; use crate::dataflow::drop_flag_effects; use crate::dataflow::indexes::{MoveOutIndex, MovePathIndex}; @@ -51,7 +51,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { &mut self, location: Location, desired_action: InitializationRequiringAction, - (moved_place, used_place, span): (PlaceRef<'tcx>, PlaceRef<'tcx>, Span), + (moved_place, used_place, span): (PlaceRef<'tcx>, PlaceRef<'tcx>, SpanId), mpi: MovePathIndex, ) { debug!( @@ -156,6 +156,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { format!("variable moved due to use{}", move_spans.describe()), ); } + let move_span = self.infcx.tcx.reify_span(move_span); if Some(DesugaringKind::ForLoop) == move_span.desugaring_kind() { let sess = self.infcx.tcx.sess; if let Ok(snippet) = sess.source_map().span_to_snippet(move_span) { @@ -247,7 +248,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { pub(in crate::borrow_check) fn report_move_out_while_borrowed( &mut self, location: Location, - (place, span): (Place<'tcx>, Span), + (place, span): (Place<'tcx>, SpanId), borrow: &BorrowData<'tcx>, ) { debug!( @@ -291,7 +292,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { pub(in crate::borrow_check) fn report_use_while_mutably_borrowed( &mut self, location: Location, - (place, _span): (Place<'tcx>, Span), + (place, _span): (Place<'tcx>, SpanId), borrow: &BorrowData<'tcx>, ) -> DiagnosticBuilder<'cx> { let borrow_spans = self.retrieve_borrow_spans(borrow); @@ -330,7 +331,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { pub(in crate::borrow_check) fn report_conflicting_borrow( &mut self, location: Location, - (place, span): (Place<'tcx>, Span), + (place, span): (Place<'tcx>, SpanId), gen_borrow_kind: BorrowKind, issued_borrow: &BorrowData<'tcx>, ) -> DiagnosticBuilder<'cx> { @@ -680,7 +681,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { &mut self, location: Location, borrow: &BorrowData<'tcx>, - place_span: (Place<'tcx>, Span), + place_span: (Place<'tcx>, SpanId), kind: Option, ) { debug!( @@ -824,7 +825,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { location: Location, name: &str, borrow: &BorrowData<'tcx>, - drop_span: Span, + drop_span: SpanId, borrow_spans: UseSpans, explanation: BorrowExplanation, ) -> DiagnosticBuilder<'cx> { @@ -945,7 +946,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { &mut self, location: Location, borrow: &BorrowData<'tcx>, - (place, drop_span): (Place<'tcx>, Span), + (place, drop_span): (Place<'tcx>, SpanId), kind: Option, dropped_ty: Ty<'tcx>, ) { @@ -1007,8 +1008,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { fn report_thread_local_value_does_not_live_long_enough( &mut self, - drop_span: Span, - borrow_span: Span, + drop_span: SpanId, + borrow_span: SpanId, ) -> DiagnosticBuilder<'cx> { debug!( "report_thread_local_value_does_not_live_long_enough(\ @@ -1032,9 +1033,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { &mut self, location: Location, borrow: &BorrowData<'tcx>, - drop_span: Span, + drop_span: SpanId, borrow_spans: UseSpans, - proper_span: Span, + proper_span: SpanId, explanation: BorrowExplanation, ) -> DiagnosticBuilder<'cx> { debug!( @@ -1090,8 +1091,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { fn try_report_cannot_return_reference_to_local( &self, borrow: &BorrowData<'tcx>, - borrow_span: Span, - return_span: Span, + borrow_span: SpanId, + return_span: SpanId, category: ConstraintCategory, opt_place_desc: Option<&String>, ) -> Option> { @@ -1162,28 +1163,29 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { fn report_escaping_closure_capture( &mut self, use_span: UseSpans, - var_span: Span, + var_span: SpanId, fr_name: &RegionName, category: ConstraintCategory, - constraint_span: Span, + constraint_span: SpanId, captured_var: &str, ) -> DiagnosticBuilder<'cx> { let tcx = self.infcx.tcx; let args_span = use_span.args_or_use(); - let suggestion = match tcx.sess.source_map().span_to_snippet(args_span) { - Ok(mut string) => { - if string.starts_with("async ") { - string.insert_str(6, "move "); - } else if string.starts_with("async|") { - string.insert_str(5, " move"); - } else { - string.insert_str(0, "move "); - }; - string - } - Err(_) => "move || ".to_string(), - }; + let suggestion = + match tcx.sess.source_map().span_to_snippet(self.infcx.tcx.reify_span(args_span)) { + Ok(mut string) => { + if string.starts_with("async ") { + string.insert_str(6, "move "); + } else if string.starts_with("async|") { + string.insert_str(5, " move"); + } else { + string.insert_str(0, "move "); + }; + string + } + Err(_) => "move || ".to_string(), + }; let kind = match use_span.generator_kind() { Some(generator_kind) => match generator_kind { GeneratorKind::Async(async_kind) => match async_kind { @@ -1229,11 +1231,11 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { fn report_escaping_data( &mut self, - borrow_span: Span, + borrow_span: SpanId, name: &Option, - upvar_span: Span, + upvar_span: SpanId, upvar_name: &str, - escape_span: Span, + escape_span: SpanId, ) -> DiagnosticBuilder<'cx> { let tcx = self.infcx.tcx; @@ -1375,7 +1377,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { pub(in crate::borrow_check) fn report_illegal_mutation_of_borrowed( &mut self, location: Location, - (place, span): (Place<'tcx>, Span), + (place, span): (Place<'tcx>, SpanId), loan: &BorrowData<'tcx>, ) { let loan_spans = self.retrieve_borrow_spans(loan); @@ -1428,8 +1430,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { pub(in crate::borrow_check) fn report_illegal_reassignment( &mut self, _location: Location, - (place, span): (Place<'tcx>, Span), - assigned_span: Span, + (place, span): (Place<'tcx>, SpanId), + assigned_span: SpanId, err_place: Place<'tcx>, ) { let (from_arg, local_decl, local_name) = match err_place.as_local() { @@ -1824,7 +1826,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { if let hir::TyKind::Rptr(lifetime, _) = &fn_decl.inputs[index].kind { // With access to the lifetime, we can get // the span of it. - arguments.push((*argument, lifetime.span)); + arguments.push((*argument, lifetime.span.into())); } else { bug!("ty type is a ref but hir type is not"); } @@ -1840,10 +1842,10 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // We use a mix of the HIR and the Ty types to get information // as the HIR doesn't have full types for closure arguments. let return_ty = *sig.output().skip_binder(); - let mut return_span = fn_decl.output.span(); + let mut return_span = fn_decl.output.span().into(); if let hir::FnRetTy::Return(ty) = &fn_decl.output { if let hir::TyKind::Rptr(lifetime, _) = ty.kind { - return_span = lifetime.span; + return_span = lifetime.span.into(); } } @@ -1857,7 +1859,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // This is case 2 from above but only for closures, return type is anonymous // reference so we select // the first argument. - let argument_span = fn_decl.inputs.first()?.span; + let argument_span = fn_decl.inputs.first()?.span.into(); let argument_ty = sig.inputs().skip_binder().first()?; // Closure arguments are wrapped in a tuple, so we need to get the first @@ -1877,10 +1879,10 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { ty::Ref(_, _, _) => { // This is also case 2 from above but for functions, return type is still an // anonymous reference so we select the first argument. - let argument_span = fn_decl.inputs.first()?.span; + let argument_span = fn_decl.inputs.first()?.span.into(); let argument_ty = sig.inputs().skip_binder().first()?; - let return_span = fn_decl.output.span(); + let return_span = fn_decl.output.span().into(); let return_ty = *sig.output().skip_binder(); // We expect the first argument to be a reference. @@ -1908,19 +1910,19 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { #[derive(Debug)] enum AnnotatedBorrowFnSignature<'tcx> { NamedFunction { - arguments: Vec<(Ty<'tcx>, Span)>, + arguments: Vec<(Ty<'tcx>, SpanId)>, return_ty: Ty<'tcx>, - return_span: Span, + return_span: SpanId, }, AnonymousFunction { argument_ty: Ty<'tcx>, - argument_span: Span, + argument_span: SpanId, return_ty: Ty<'tcx>, - return_span: Span, + return_span: SpanId, }, Closure { argument_ty: Ty<'tcx>, - argument_span: Span, + argument_span: SpanId, }, } diff --git a/src/librustc_mir/borrow_check/diagnostics/explain_borrow.rs b/src/librustc_mir/borrow_check/diagnostics/explain_borrow.rs index 5253acbba7f1c..1dba7ee803b00 100644 --- a/src/librustc_mir/borrow_check/diagnostics/explain_borrow.rs +++ b/src/librustc_mir/borrow_check/diagnostics/explain_borrow.rs @@ -13,7 +13,7 @@ use rustc_middle::mir::{ use rustc_middle::ty::adjustment::PointerCast; use rustc_middle::ty::{self, RegionVid, TyCtxt}; use rustc_span::symbol::Symbol; -use rustc_span::Span; +use rustc_span::SpanId; use crate::borrow_check::{ borrow_set::BorrowData, nll::ConstraintDescription, region_infer::Cause, MirBorrowckCtxt, @@ -24,8 +24,8 @@ use super::{find_use, RegionName, UseSpans}; #[derive(Debug)] pub(in crate::borrow_check) enum BorrowExplanation { - UsedLater(LaterUseKind, Span), - UsedLaterInLoop(LaterUseKind, Span), + UsedLater(LaterUseKind, SpanId), + UsedLaterInLoop(LaterUseKind, SpanId), UsedLaterWhenDropped { drop_loc: Location, dropped_local: Local, @@ -34,7 +34,7 @@ pub(in crate::borrow_check) enum BorrowExplanation { MustBeValidFor { category: ConstraintCategory, from_closure: bool, - span: Span, + span: SpanId, region_name: RegionName, opt_place_desc: Option, }, @@ -64,7 +64,7 @@ impl BorrowExplanation { local_names: &IndexVec>, err: &mut DiagnosticBuilder<'_>, borrow_desc: &str, - borrow_span: Option, + borrow_span: Option, ) { match *self { BorrowExplanation::UsedLater(later_use_kind, var_or_use_span) => { @@ -75,7 +75,10 @@ impl BorrowExplanation { LaterUseKind::FakeLetRead => "stored here", LaterUseKind::Other => "used here", }; - if !borrow_span.map(|sp| sp.overlaps(var_or_use_span)).unwrap_or(false) { + if !borrow_span + .map(|sp| tcx.reify_span(sp).overlaps(tcx.reify_span(var_or_use_span))) + .unwrap_or(false) + { err.span_label( var_or_use_span, format!("{}borrow later {}", borrow_desc, message), @@ -118,7 +121,7 @@ impl BorrowExplanation { }; match local_names[dropped_local] { - Some(local_name) if !local_decl.from_compiler_desugaring() => { + Some(local_name) if !local_decl.from_compiler_desugaring(tcx) => { let message = format!( "{B}borrow might be used here, when `{LOC}` is dropped \ and runs the {DTOR} for {TYPE}", @@ -156,9 +159,10 @@ impl BorrowExplanation { err.span_label(body.source_info(drop_loc).span, message); if let Some(info) = &local_decl.is_block_tail { + let info_span = tcx.reify_span(info.span); if info.tail_result_is_ignored { err.span_suggestion_verbose( - info.span.shrink_to_hi(), + info_span.shrink_to_hi(), "consider adding semicolon after the expression so its \ temporaries are dropped sooner, before the local variables \ declared by the block are dropped", @@ -176,8 +180,8 @@ impl BorrowExplanation { local variable `x` and then make `x` be the expression at the \ end of the block", vec![ - (info.span.shrink_to_lo(), "let x = ".to_string()), - (info.span.shrink_to_hi(), "; x".to_string()), + (info_span.shrink_to_lo(), "let x = ".to_string()), + (info_span.shrink_to_hi(), "; x".to_string()), ], Applicability::MaybeIncorrect, ); @@ -217,16 +221,23 @@ impl BorrowExplanation { ); }; - self.add_lifetime_bound_suggestion_to_diagnostic(err, &category, span, region_name); + self.add_lifetime_bound_suggestion_to_diagnostic( + tcx, + err, + &category, + span, + region_name, + ); } _ => {} } } pub(in crate::borrow_check) fn add_lifetime_bound_suggestion_to_diagnostic( &self, + tcx: TyCtxt<'_>, err: &mut DiagnosticBuilder<'_>, category: &ConstraintCategory, - span: Span, + span: SpanId, region_name: &RegionName, ) { if let ConstraintCategory::OpaqueType = category { @@ -240,7 +251,7 @@ impl BorrowExplanation { ); err.span_suggestion_verbose( - span.shrink_to_hi(), + tcx.reify_span(span).shrink_to_hi(), &msg, format!(" + {}", suggestable_name), Applicability::Unspecified, @@ -254,7 +265,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { &self, borrow_region: RegionVid, outlived_region: RegionVid, - ) -> (ConstraintCategory, bool, Span, Option) { + ) -> (ConstraintCategory, bool, SpanId, Option) { let (category, from_closure, span) = self.regioncx.best_blame_constraint( &self.body, borrow_region, @@ -503,7 +514,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { borrow: &BorrowData<'tcx>, use_spans: UseSpans, location: Location, - ) -> (LaterUseKind, Span) { + ) -> (LaterUseKind, SpanId) { match use_spans { UseSpans::ClosureUse { var_span, .. } => { // Used in a closure. diff --git a/src/librustc_mir/borrow_check/diagnostics/mod.rs b/src/librustc_mir/borrow_check/diagnostics/mod.rs index c218e3906fff2..f0932e8d51fe2 100644 --- a/src/librustc_mir/borrow_check/diagnostics/mod.rs +++ b/src/librustc_mir/borrow_check/diagnostics/mod.rs @@ -11,7 +11,7 @@ use rustc_middle::mir::{ }; use rustc_middle::ty::print::Print; use rustc_middle::ty::{self, DefIdTree, Ty, TyCtxt}; -use rustc_span::{symbol::sym, Span}; +use rustc_span::{symbol::sym, SpanId}; use rustc_target::abi::VariantIdx; use super::borrow_set::BorrowData; @@ -311,7 +311,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { fn append_local_to_string(&self, local: Local, buf: &mut String) -> Result<(), ()> { let decl = &self.body.local_decls[local]; match self.local_names[local] { - Some(name) if !decl.from_compiler_desugaring() => { + Some(name) if !decl.from_compiler_desugaring(self.infcx.tcx) => { buf.push_str(&name.as_str()); Ok(()) } @@ -400,7 +400,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { err: &mut DiagnosticBuilder<'a>, place_desc: &str, ty: Ty<'tcx>, - span: Option, + span: Option, ) { let message = format!( "move occurs because {} has type `{}`, which does not implement the `Copy` trait", @@ -533,22 +533,22 @@ pub(super) enum UseSpans { generator_kind: Option, // The span of the args of the closure, including the `move` keyword if // it's present. - args_span: Span, + args_span: SpanId, // The span of the first use of the captured variable inside the closure. - var_span: Span, + var_span: SpanId, }, // This access has a single span associated to it: common case. - OtherUse(Span), + OtherUse(SpanId), } impl UseSpans { - pub(super) fn args_or_use(self) -> Span { + pub(super) fn args_or_use(self) -> SpanId { match self { UseSpans::ClosureUse { args_span: span, .. } | UseSpans::OtherUse(span) => span, } } - pub(super) fn var_or_use(self) -> Span { + pub(super) fn var_or_use(self) -> SpanId { match self { UseSpans::ClosureUse { var_span: span, .. } | UseSpans::OtherUse(span) => span, } @@ -743,7 +743,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { /// and its usage of the local assigned at `location`. /// This is done by searching in statements succeeding `location` /// and originating from `maybe_closure_span`. - pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans { + pub(super) fn borrow_spans(&self, use_span: SpanId, location: Location) -> UseSpans { use self::UseSpans::*; debug!("borrow_spans: use_span={:?} location={:?}", use_span, location); @@ -800,7 +800,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { def_id: DefId, target_place: PlaceRef<'tcx>, places: &Vec>, - ) -> Option<(Span, Option, Span)> { + ) -> Option<(SpanId, Option, SpanId)> { debug!( "closure_span: def_id={:?} target_place={:?} places={:?}", def_id, target_place, places @@ -817,7 +817,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { debug!("closure_span: found captured local {:?}", place); let body = self.infcx.tcx.hir().body(*body_id); let generator_kind = body.generator_kind(); - return Some((*args_span, generator_kind, upvar.span)); + return Some(((*args_span).into(), generator_kind, upvar.span.into())); } _ => {} } diff --git a/src/librustc_mir/borrow_check/diagnostics/move_errors.rs b/src/librustc_mir/borrow_check/diagnostics/move_errors.rs index 67254811ec52a..ac8371e2b0ba2 100644 --- a/src/librustc_mir/borrow_check/diagnostics/move_errors.rs +++ b/src/librustc_mir/borrow_check/diagnostics/move_errors.rs @@ -2,7 +2,7 @@ use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_middle::mir::*; use rustc_middle::ty; use rustc_span::source_map::DesugaringKind; -use rustc_span::{Span, Symbol}; +use rustc_span::{SpanId, Symbol}; use crate::borrow_check::diagnostics::UseSpans; use crate::borrow_check::prefixes::PrefixSet; @@ -30,7 +30,7 @@ enum GroupedMoveError<'tcx> { // e.g., match x[0] { s => (), } where x: &[String] MovesFromPlace { original_path: Place<'tcx>, - span: Span, + span: SpanId, move_from: Place<'tcx>, kind: IllegalMoveOriginKind<'tcx>, binds_to: Vec, @@ -39,7 +39,7 @@ enum GroupedMoveError<'tcx> { // e.g., match &String::new() { &x => (), } MovesFromValue { original_path: Place<'tcx>, - span: Span, + span: SpanId, move_from: MovePathIndex, kind: IllegalMoveOriginKind<'tcx>, binds_to: Vec, @@ -146,8 +146,8 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { move_from: Place<'tcx>, bind_to: Local, match_place: Option>, - match_span: Span, - statement_span: Span, + match_span: SpanId, + statement_span: SpanId, ) { debug!("append_binding_error(match_place={:?}, match_span={:?})", match_place, match_span); @@ -221,7 +221,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { fn report(&mut self, error: GroupedMoveError<'tcx>) { let (mut err, err_span) = { let (span, use_spans, original_path, kind): ( - Span, + SpanId, Option, Place<'tcx>, &IllegalMoveOriginKind<'_>, @@ -269,7 +269,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { fn report_cannot_move_from_static( &mut self, place: Place<'tcx>, - span: Span, + span: SpanId, ) -> DiagnosticBuilder<'a> { let description = if place.projection.len() == 1 { format!("static item {}", self.describe_any_place(place.as_ref())) @@ -290,7 +290,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { &mut self, move_place: Place<'tcx>, deref_target_place: Place<'tcx>, - span: Span, + span: SpanId, use_spans: Option, ) -> DiagnosticBuilder<'a> { // Inspect the type of the content behind the @@ -384,6 +384,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { } } }; + let span = self.infcx.tcx.reify_span(span); if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) { let def_id = match move_place.ty(self.body, self.infcx.tcx).ty.kind { ty::Adt(self_def, _) => self_def.did, @@ -427,11 +428,17 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { &self, error: GroupedMoveError<'tcx>, err: &mut DiagnosticBuilder<'a>, - span: Span, + span: SpanId, ) { match error { GroupedMoveError::MovesFromPlace { mut binds_to, move_from, .. } => { - if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) { + if let Ok(snippet) = self + .infcx + .tcx + .sess + .source_map() + .span_to_snippet(self.infcx.tcx.reify_span(span)) + { err.span_suggestion( span, "consider borrowing here", @@ -479,14 +486,19 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { } fn add_move_error_suggestions(&self, err: &mut DiagnosticBuilder<'a>, binds_to: &[Local]) { - let mut suggestions: Vec<(Span, &str, String)> = Vec::new(); + let mut suggestions: Vec<(SpanId, &str, String)> = Vec::new(); for local in binds_to { let bind_to = &self.body.local_decls[*local]; if let Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var( VarBindingForm { pat_span, .. }, )))) = bind_to.local_info { - if let Ok(pat_snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(pat_span) + if let Ok(pat_snippet) = self + .infcx + .tcx + .sess + .source_map() + .span_to_snippet(self.infcx.tcx.reify_span(pat_span)) { if pat_snippet.starts_with('&') { let pat_snippet = pat_snippet[1..].trim_start(); diff --git a/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs b/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs index 402eac47c462b..a421ace21f82b 100644 --- a/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs +++ b/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs @@ -6,7 +6,7 @@ use rustc_middle::mir::{Mutability, Place, PlaceRef, ProjectionElem}; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::source_map::DesugaringKind; use rustc_span::symbol::kw; -use rustc_span::Span; +use rustc_span::SpanId; use crate::borrow_check::diagnostics::BorrowedContentSource; use crate::borrow_check::MirBorrowckCtxt; @@ -23,7 +23,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { pub(crate) fn report_mutability_error( &mut self, access_place: Place<'tcx>, - span: Span, + span: SpanId, the_place_err: PlaceRef<'tcx>, error_access: AccessKind, location: Location, @@ -302,7 +302,13 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { // a local variable, then just suggest the user remove it. PlaceRef { local: _, projection: [] } if { - if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) { + if let Ok(snippet) = self + .infcx + .tcx + .sess + .source_map() + .span_to_snippet(self.infcx.tcx.reify_span(span)) + { snippet.starts_with("&mut ") } else { false @@ -339,7 +345,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { }; match self.local_names[local] { - Some(name) if !local_decl.from_compiler_desugaring() => { + Some(name) if !local_decl.from_compiler_desugaring(self.infcx.tcx) => { let label = match local_decl.local_info.as_ref().unwrap() { box LocalInfo::User(ClearCrossCrate::Set( mir::BindingForm::ImplicitSelf(_), @@ -362,7 +368,9 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { .first() .map(|&location| self.body.source_info(location).span); let opt_desugaring_kind = - opt_assignment_rhs_span.and_then(|span| span.desugaring_kind()); + opt_assignment_rhs_span.and_then(|span| { + self.infcx.tcx.reify_span(span).desugaring_kind() + }); match opt_desugaring_kind { // on for loops, RHS points to the iterator part Some(DesugaringKind::ForLoop) => Some(( @@ -488,7 +496,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { } /// Targeted error when encountering an `FnMut` closure where an `Fn` closure was expected. - fn expected_fn_found_fn_mut_call(&self, err: &mut DiagnosticBuilder<'_>, sp: Span, act: &str) { + fn expected_fn_found_fn_mut_call( + &self, + err: &mut DiagnosticBuilder<'_>, + sp: SpanId, + act: &str, + ) { err.span_label(sp, format!("cannot {}", act)); let hir = self.infcx.tcx.hir(); @@ -500,10 +513,11 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { // If we can detect the expression to be an `fn` call where the closure was an argument, // we point at the `fn` definition argument... if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Call(func, args), .. }) = node { + let body_span = self.infcx.tcx.reify_span(self.body.span); let arg_pos = args .iter() .enumerate() - .filter(|(_, arg)| arg.span == self.body.span) + .filter(|(_, arg)| arg.span == body_span) .map(|(pos, _)| pos) .next(); let def_id = hir.local_def_id(item_id); @@ -545,7 +559,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { if let Some(span) = arg { err.span_label(span, "change this to accept `FnMut` instead of `Fn`"); err.span_label(func.span, "expects `Fn` instead of `FnMut`"); - if self.infcx.tcx.sess.source_map().is_multiline(self.body.span) { + if self.infcx.tcx.sess.source_map().is_multiline(body_span) { err.span_label(self.body.span, "in this closure"); } look_at_return = false; @@ -584,11 +598,11 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { fn suggest_ampmut_self<'tcx>( tcx: TyCtxt<'tcx>, local_decl: &mir::LocalDecl<'tcx>, -) -> (Span, String) { +) -> (SpanId, String) { let sp = local_decl.source_info.span; ( sp, - match tcx.sess.source_map().span_to_snippet(sp) { + match tcx.sess.source_map().span_to_snippet(tcx.reify_span(sp)) { Ok(snippet) => { let lt_pos = snippet.find('\''); if let Some(lt_pos) = lt_pos { @@ -620,11 +634,12 @@ fn suggest_ampmut_self<'tcx>( fn suggest_ampmut<'tcx>( tcx: TyCtxt<'tcx>, local_decl: &mir::LocalDecl<'tcx>, - opt_assignment_rhs_span: Option, - opt_ty_info: Option, -) -> (Span, String) { + opt_assignment_rhs_span: Option, + opt_ty_info: Option, +) -> (SpanId, String) { if let Some(assignment_rhs_span) = opt_assignment_rhs_span { - if let Ok(src) = tcx.sess.source_map().span_to_snippet(assignment_rhs_span) { + if let Ok(src) = tcx.sess.source_map().span_to_snippet(tcx.reify_span(assignment_rhs_span)) + { if let (true, Some(ws_pos)) = (src.starts_with("&'"), src.find(|c: char| -> bool { c.is_whitespace() })) { @@ -648,7 +663,7 @@ fn suggest_ampmut<'tcx>( None => local_decl.source_info.span, }; - if let Ok(src) = tcx.sess.source_map().span_to_snippet(highlight_span) { + if let Ok(src) = tcx.sess.source_map().span_to_snippet(tcx.reify_span(highlight_span)) { if let (true, Some(ws_pos)) = (src.starts_with("&'"), src.find(|c: char| -> bool { c.is_whitespace() })) { @@ -685,7 +700,7 @@ fn annotate_struct_field( tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, field: &mir::Field, -) -> Option<(Span, String)> { +) -> Option<(SpanId, String)> { // Expect our local to be a reference to a struct of some kind. if let ty::Ref(_, ty, _) = ty.kind { if let ty::Adt(def, _) = ty.kind { @@ -712,7 +727,7 @@ fn annotate_struct_field( }; return Some(( - field.ty.span, + field.ty.span.into(), format!("&{}mut {}", lifetime_snippet, &*type_snippet,), )); } @@ -724,8 +739,8 @@ fn annotate_struct_field( } /// If possible, suggest replacing `ref` with `ref mut`. -fn suggest_ref_mut(tcx: TyCtxt<'_>, binding_span: Span) -> Option { - let hi_src = tcx.sess.source_map().span_to_snippet(binding_span).ok()?; +fn suggest_ref_mut(tcx: TyCtxt<'_>, binding_span: SpanId) -> Option { + let hi_src = tcx.sess.source_map().span_to_snippet(tcx.reify_span(binding_span)).ok()?; if hi_src.starts_with("ref") && hi_src["ref".len()..].starts_with(rustc_lexer::is_whitespace) { let replacement = format!("ref mut{}", &hi_src["ref".len()..]); Some(replacement) diff --git a/src/librustc_mir/borrow_check/diagnostics/outlives_suggestion.rs b/src/librustc_mir/borrow_check/diagnostics/outlives_suggestion.rs index dd970d800fba0..043c8ce2ee623 100644 --- a/src/librustc_mir/borrow_check/diagnostics/outlives_suggestion.rs +++ b/src/librustc_mir/borrow_check/diagnostics/outlives_suggestion.rs @@ -259,8 +259,8 @@ impl OutlivesSuggestionBuilder { }; // We want this message to appear after other messages on the mir def. - let mir_span = mbcx.infcx.tcx.def_span(mbcx.mir_def_id); - diag.sort_span = mir_span.shrink_to_hi(); + let mir_span = mbcx.infcx.tcx.real_def_span(mbcx.mir_def_id); + diag.sort_span = mir_span.shrink_to_hi().into(); // Buffer the diagnostic diag.buffer(&mut mbcx.errors_buffer); diff --git a/src/librustc_mir/borrow_check/diagnostics/region_errors.rs b/src/librustc_mir/borrow_check/diagnostics/region_errors.rs index 98c0542f9c0dc..492d6e5fb335e 100644 --- a/src/librustc_mir/borrow_check/diagnostics/region_errors.rs +++ b/src/librustc_mir/borrow_check/diagnostics/region_errors.rs @@ -8,7 +8,7 @@ use rustc_infer::infer::{ use rustc_middle::mir::ConstraintCategory; use rustc_middle::ty::{self, RegionVid, Ty}; use rustc_span::symbol::kw; -use rustc_span::Span; +use rustc_span::SpanId; use crate::util::borrowck_errors; @@ -59,7 +59,7 @@ crate enum RegionErrorKind<'tcx> { /// An unexpected hidden region for an opaque type. UnexpectedHiddenRegion { /// The span for the member constraint. - span: Span, + span: SpanId, /// The hidden type. hidden_ty: Ty<'tcx>, /// The unexpected region. @@ -101,7 +101,7 @@ pub struct ErrorConstraintInfo { // Category and span for best blame constraint pub(super) category: ConstraintCategory, - pub(super) span: Span, + pub(super) span: SpanId, } impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { @@ -166,7 +166,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { self.infcx .construct_generic_bound_failure( region_scope_tree, - type_test_span, + self.infcx.tcx.reify_span(type_test_span), None, type_test.generic_kind, lower_bound_region, @@ -200,7 +200,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { unexpected_hidden_region_diagnostic( self.infcx.tcx, Some(region_scope_tree), - span, + self.infcx.tcx.reify_span(span), named_ty, named_region, ) @@ -283,7 +283,8 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { debug!("report_region_error: category={:?} {:?}", category, span); // Check if we can use one of the "nice region errors". if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) { - let nice = NiceRegionError::new_from_span(self.infcx, span, o, f); + let nice = + NiceRegionError::new_from_span(self.infcx, self.infcx.tcx.reify_span(span), o, f); if let Some(diag) = nice.try_report_from_nll() { diag.buffer(&mut self.errors_buffer); return; @@ -604,7 +605,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { diag.help(&format!("consider replacing `{}` with `{}`", fr_name, static_str)); } else { // Otherwise, we should suggest adding a constraint on the return type. - let span = self.infcx.tcx.def_span(*did); + let span = self.infcx.tcx.real_def_span(*did); if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) { let suggestable_fr_name = if fr_name.was_named() { fr_name.to_string() diff --git a/src/librustc_mir/borrow_check/diagnostics/region_name.rs b/src/librustc_mir/borrow_check/diagnostics/region_name.rs index 37e2e0475048d..3dddd993404a6 100644 --- a/src/librustc_mir/borrow_check/diagnostics/region_name.rs +++ b/src/librustc_mir/borrow_check/diagnostics/region_name.rs @@ -7,7 +7,7 @@ use rustc_middle::ty::print::RegionHighlightMode; use rustc_middle::ty::subst::{GenericArgKind, SubstsRef}; use rustc_middle::ty::{self, RegionVid, Ty}; use rustc_span::symbol::kw; -use rustc_span::{symbol::Symbol, Span, DUMMY_SP}; +use rustc_span::{symbol::Symbol, SpanId, DUMMY_SP}; use crate::borrow_check::{nll::ToRegionVid, universal_regions::DefiningTy, MirBorrowckCtxt}; @@ -27,28 +27,28 @@ crate struct RegionName { #[derive(Debug, Clone)] crate enum RegionNameSource { /// A bound (not free) region that was substituted at the def site (not an HRTB). - NamedEarlyBoundRegion(Span), + NamedEarlyBoundRegion(SpanId), /// A free region that the user has a name (`'a`) for. - NamedFreeRegion(Span), + NamedFreeRegion(SpanId), /// The `'static` region. Static, /// The free region corresponding to the environment of a closure. - SynthesizedFreeEnvRegion(Span, String), + SynthesizedFreeEnvRegion(SpanId, String), /// The region name corresponds to a region where the type annotation is completely missing /// from the code, e.g. in a closure arguments `|x| { ... }`, where `x` is a reference. - CannotMatchHirTy(Span, String), + CannotMatchHirTy(SpanId, String), /// The region name corresponds a reference that was found by traversing the type in the HIR. - MatchedHirTy(Span), + MatchedHirTy(SpanId), /// A region name from the generics list of a struct/enum/union. - MatchedAdtAndSegment(Span), + MatchedAdtAndSegment(SpanId), /// The region corresponding to a closure upvar. - AnonRegionFromUpvar(Span, String), + AnonRegionFromUpvar(SpanId, String), /// The region corresponding to the return type of a closure. - AnonRegionFromOutput(Span, String, String), + AnonRegionFromOutput(SpanId, String, String), /// The region from a type yielded by a generator. - AnonRegionFromYieldTy(Span, String), + AnonRegionFromYieldTy(SpanId, String), /// An anonymous region from an async fn. - AnonRegionFromAsyncFn(Span), + AnonRegionFromAsyncFn(SpanId), } impl RegionName { @@ -195,7 +195,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { match error_region { ty::ReEarlyBound(ebr) => { if ebr.has_name() { - let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP); + let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP).into(); Some(RegionName { name: ebr.name, source: RegionNameSource::NamedEarlyBoundRegion(span), @@ -212,7 +212,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { ty::ReFree(free_region) => match free_region.bound_region { ty::BoundRegion::BrNamed(region_def_id, name) => { // Get the span to point to, even if we don't use the name. - let span = tcx.hir().span_if_local(region_def_id).unwrap_or(DUMMY_SP); + let span = tcx.hir().span_if_local(region_def_id).unwrap_or(DUMMY_SP).into(); debug!( "bound region named: {:?}, is_named: {:?}", name, @@ -270,7 +270,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { Some(RegionName { name: region_name, source: RegionNameSource::SynthesizedFreeEnvRegion( - args_span, + args_span.into(), note.to_string(), ), }) @@ -435,7 +435,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { // Just grab the first character, the `&`. let source_map = self.infcx.tcx.sess.source_map(); - let ampersand_span = source_map.start_point(hir_ty.span); + let ampersand_span = source_map.start_point(hir_ty.span).into(); return Some(RegionName { name: region_name, @@ -520,7 +520,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { | hir::LifetimeName::Static | hir::LifetimeName::Underscore => { let region_name = self.synthesize_region_name(); - let ampersand_span = lifetime.span; + let ampersand_span = lifetime.span.into(); Some(RegionName { name: region_name, source: RegionNameSource::MatchedAdtAndSegment(ampersand_span), @@ -643,15 +643,15 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { .. }) => ( match return_ty.output { - hir::FnRetTy::DefaultReturn(_) => tcx.sess.source_map().end_point(*span), - hir::FnRetTy::Return(_) => return_ty.output.span(), + hir::FnRetTy::DefaultReturn(_) => tcx.sess.source_map().end_point(*span).into(), + hir::FnRetTy::Return(_) => return_ty.output.span().into(), }, if gen_move.is_some() { " of generator" } else { " of closure" }, ), hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(method_sig, _), .. - }) => (method_sig.decl.output.span(), ""), + }) => (method_sig.decl.output.span().into(), ""), _ => (self.body.span, ""), }; @@ -692,7 +692,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { let yield_span = match tcx.hir().get(mir_hir_id) { hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, _, _, span, _), .. - }) => (tcx.sess.source_map().end_point(*span)), + }) => tcx.sess.source_map().end_point(*span).into(), _ => self.body.span, }; diff --git a/src/librustc_mir/borrow_check/diagnostics/var_name.rs b/src/librustc_mir/borrow_check/diagnostics/var_name.rs index a850b85e9bbae..19cc199e473a0 100644 --- a/src/librustc_mir/borrow_check/diagnostics/var_name.rs +++ b/src/librustc_mir/borrow_check/diagnostics/var_name.rs @@ -3,7 +3,7 @@ use crate::borrow_check::{nll::ToRegionVid, region_infer::RegionInferenceContext use rustc_index::vec::{Idx, IndexVec}; use rustc_middle::mir::{Body, Local}; use rustc_middle::ty::{RegionVid, TyCtxt}; -use rustc_span::source_map::Span; +use rustc_span::source_map::SpanId; use rustc_span::symbol::Symbol; impl<'tcx> RegionInferenceContext<'tcx> { @@ -14,7 +14,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { local_names: &IndexVec>, upvars: &[Upvar], fr: RegionVid, - ) -> Option<(Option, Span)> { + ) -> Option<(Option, SpanId)> { debug!("get_var_name_and_span_for_region(fr={:?})", fr); assert!(self.universal_regions().is_universal_region(fr)); @@ -61,12 +61,12 @@ impl<'tcx> RegionInferenceContext<'tcx> { tcx: TyCtxt<'tcx>, upvars: &[Upvar], upvar_index: usize, - ) -> (Symbol, Span) { + ) -> (Symbol, SpanId) { let upvar_hir_id = upvars[upvar_index].var_hir_id; debug!("get_upvar_name_and_span_for_region: upvar_hir_id={:?}", upvar_hir_id); let upvar_name = tcx.hir().name(upvar_hir_id); - let upvar_span = tcx.hir().span(upvar_hir_id); + let upvar_span = tcx.hir().span(upvar_hir_id).into(); debug!( "get_upvar_name_and_span_for_region: upvar_name={:?} upvar_span={:?}", upvar_name, upvar_span @@ -111,7 +111,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { body: &Body<'tcx>, local_names: &IndexVec>, argument_index: usize, - ) -> (Option, Span) { + ) -> (Option, SpanId) { let implicit_inputs = self.universal_regions().defining_ty.implicit_inputs(); let argument_local = Local::new(implicit_inputs + argument_index + 1); debug!("get_argument_name_and_span_for_region: argument_local={:?}", argument_local); diff --git a/src/librustc_mir/borrow_check/member_constraints.rs b/src/librustc_mir/borrow_check/member_constraints.rs index d4baa5d809a22..fbdf74b2a02c2 100644 --- a/src/librustc_mir/borrow_check/member_constraints.rs +++ b/src/librustc_mir/borrow_check/member_constraints.rs @@ -3,7 +3,7 @@ use rustc_hir::def_id::DefId; use rustc_index::vec::IndexVec; use rustc_middle::infer::MemberConstraint; use rustc_middle::ty::{self, Ty}; -use rustc_span::Span; +use rustc_span::SpanId; use std::hash::Hash; use std::ops::Index; @@ -36,7 +36,7 @@ crate struct NllMemberConstraint<'tcx> { crate opaque_type_def_id: DefId, /// The span where the hidden type was instantiated. - crate definition_span: Span, + crate definition_span: SpanId, /// The hidden type in which `R0` appears. (Used in error reporting.) crate hidden_ty: Ty<'tcx>, @@ -92,7 +92,7 @@ impl<'tcx> MemberConstraintSet<'tcx, ty::RegionVid> { next_constraint, member_region_vid, opaque_type_def_id: m_c.opaque_type_def_id, - definition_span: m_c.definition_span, + definition_span: m_c.definition_span.into(), hidden_ty: m_c.hidden_ty, start_index, end_index, diff --git a/src/librustc_mir/borrow_check/mod.rs b/src/librustc_mir/borrow_check/mod.rs index a3ee49651ba7b..f8c5885f47812 100644 --- a/src/librustc_mir/borrow_check/mod.rs +++ b/src/librustc_mir/borrow_check/mod.rs @@ -21,7 +21,7 @@ use rustc_middle::mir::{Terminator, TerminatorKind}; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, RegionVid, TyCtxt}; use rustc_session::lint::builtin::{MUTABLE_BORROW_RESERVATION_CONFLICT, UNUSED_MUT}; -use rustc_span::{Span, Symbol, DUMMY_SP}; +use rustc_span::{SpanId, Symbol, DUMMY_SPID}; use either::Either; use smallvec::SmallVec; @@ -359,11 +359,11 @@ fn do_mir_borrowck<'a, 'tcx>( _ => id, }; - // Span and message don't matter; we overwrite them below anyway + // SpanId and message don't matter; we overwrite them below anyway mbcx.infcx.tcx.struct_span_lint_hir( MUTABLE_BORROW_RESERVATION_CONFLICT, lint_root, - DUMMY_SP, + DUMMY_SPID, |lint| { let mut diag = lint.build(""); @@ -413,7 +413,7 @@ fn do_mir_borrowck<'a, 'tcx>( None => continue, } - let span = local_decl.source_info.span; + let span = tcx.reify_span(local_decl.source_info.span); if span.desugaring_kind().is_some() { // If the `mut` arises as part of a desugaring, we should ignore it. continue; @@ -441,7 +441,7 @@ fn do_mir_borrowck<'a, 'tcx>( mbcx.errors_buffer.sort_by_key(|diag| diag.sort_span); for diag in mbcx.errors_buffer.drain(..) { - mbcx.infcx.tcx.sess.diagnostic().emit_diagnostic(&diag); + mbcx.infcx.tcx.sess.diagnostic().emit_diagnostic(diag); } } @@ -477,9 +477,9 @@ crate struct MirBorrowckCtxt<'cx, 'tcx> { /// This field keeps track of when borrow errors are reported in the access_place function /// so that there is no duplicate reporting. This field cannot also be used for the conflicting /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion - /// of the `Span` type (while required to mute some errors) stops the muting of the reservation + /// of the `SpanId` type (while required to mute some errors) stops the muting of the reservation /// errors. - access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>, + access_place_error_reported: FxHashSet<(Place<'tcx>, SpanId)>, /// This field keeps track of when borrow conflict errors are reported /// for reservations, so that we don't report seemingly duplicate /// errors for corresponding activations. @@ -492,7 +492,7 @@ crate struct MirBorrowckCtxt<'cx, 'tcx> { /// so that we can suppress the warning if there's a corresponding error /// for the activation of the borrow. reservation_warnings: - FxHashMap, Span, Location, BorrowKind, BorrowData<'tcx>)>, + FxHashMap, SpanId, Location, BorrowKind, BorrowData<'tcx>)>, /// This field keeps track of move errors that are to be reported for given move indices. /// /// There are situations where many errors can be reported for a single move out (see #53807) @@ -599,7 +599,7 @@ impl<'cx, 'tcx> dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tc // be encoded through MIR place derefs instead. self.access_place( location, - (*output, o.span), + (*output, o.span.into()), (Deep, Read(ReadKind::Copy)), LocalMutationIsAllowed::No, flow_state, @@ -607,13 +607,13 @@ impl<'cx, 'tcx> dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tc self.check_if_path_or_subpath_is_moved( location, InitializationRequiringAction::Use, - (output.as_ref(), o.span), + (output.as_ref(), o.span.into()), flow_state, ); } else { self.mutate_place( location, - (*output, o.span), + (*output, o.span.into()), if o.is_rw { Deep } else { Shallow(None) }, if o.is_rw { WriteAndRead } else { JustWrite }, flow_state, @@ -926,7 +926,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { fn access_place( &mut self, location: Location, - place_span: (Place<'tcx>, Span), + place_span: (Place<'tcx>, SpanId), kind: (AccessDepth, ReadOrWrite), is_local_mutation_allowed: LocalMutationIsAllowed, flow_state: &Flows<'cx, 'tcx>, @@ -982,7 +982,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { fn check_access_for_conflict( &mut self, location: Location, - place_span: (Place<'tcx>, Span), + place_span: (Place<'tcx>, SpanId), sd: AccessDepth, rw: ReadOrWrite, flow_state: &Flows<'cx, 'tcx>, @@ -1140,7 +1140,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { fn mutate_place( &mut self, location: Location, - place_span: (Place<'tcx>, Span), + place_span: (Place<'tcx>, SpanId), kind: AccessDepth, mode: MutateMode, flow_state: &Flows<'cx, 'tcx>, @@ -1186,7 +1186,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { fn consume_rvalue( &mut self, location: Location, - (rvalue, span): (&'cx Rvalue<'tcx>, Span), + (rvalue, span): (&'cx Rvalue<'tcx>, SpanId), flow_state: &Flows<'cx, 'tcx>, ) { match *rvalue { @@ -1396,7 +1396,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { fn consume_operand( &mut self, location: Location, - (operand, span): (&'cx Operand<'tcx>, Span), + (operand, span): (&'cx Operand<'tcx>, SpanId), flow_state: &Flows<'cx, 'tcx>, ) { match *operand { @@ -1447,7 +1447,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { &mut self, location: Location, borrow: &BorrowData<'tcx>, - span: Span, + span: SpanId, ) { debug!("check_for_invalidation_at_exit({:?})", borrow); let place = borrow.borrowed_place; @@ -1489,7 +1489,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { debug!("check_for_invalidation_at_exit({:?}): INVALID", place); // FIXME: should be talking about the region lifetime instead // of just a span here. - let span = self.infcx.tcx.sess.source_map().end_point(span); + let span = + self.infcx.tcx.sess.source_map().end_point(self.infcx.tcx.reify_span(span)).into(); self.report_borrowed_value_does_not_live_long_enough( location, borrow, @@ -1501,7 +1502,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { /// Reports an error if this is a borrow of local data. /// This is called for all Yield expressions on movable generators - fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) { + fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: SpanId) { debug!("check_for_local_borrow({:?})", borrow); if borrow_of_local_data(borrow.borrowed_place) { @@ -1514,7 +1515,12 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } } - fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) { + fn check_activations( + &mut self, + location: Location, + span: SpanId, + flow_state: &Flows<'cx, 'tcx>, + ) { // Two-phase borrow support: For each activation that is newly // generated at this statement, check if it interferes with // another borrow. @@ -1545,7 +1551,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { &mut self, location: Location, local: Local, - place_span: (Place<'tcx>, Span), + place_span: (Place<'tcx>, SpanId), flow_state: &Flows<'cx, 'tcx>, ) { debug!("check_if_reassignment_to_immutable_state({:?})", local); @@ -1563,7 +1569,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { &mut self, location: Location, desired_action: InitializationRequiringAction, - place_span: (PlaceRef<'tcx>, Span), + place_span: (PlaceRef<'tcx>, SpanId), flow_state: &Flows<'cx, 'tcx>, ) { let maybe_uninits = &flow_state.uninits; @@ -1629,7 +1635,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { &mut self, location: Location, desired_action: InitializationRequiringAction, - place_span: (PlaceRef<'tcx>, Span), + place_span: (PlaceRef<'tcx>, SpanId), maybe_uninits: &BitSet, from: u32, to: u32, @@ -1668,7 +1674,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { &mut self, location: Location, desired_action: InitializationRequiringAction, - place_span: (PlaceRef<'tcx>, Span), + place_span: (PlaceRef<'tcx>, SpanId), flow_state: &Flows<'cx, 'tcx>, ) { let maybe_uninits = &flow_state.uninits; @@ -1769,7 +1775,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { fn check_if_assigned_path_is_moved( &mut self, location: Location, - (place, span): (Place<'tcx>, Span), + (place, span): (Place<'tcx>, SpanId), flow_state: &Flows<'cx, 'tcx>, ) { debug!("check_if_assigned_path_is_moved place: {:?}", place); @@ -1851,7 +1857,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { this: &mut MirBorrowckCtxt<'cx, 'tcx>, location: Location, base: PlaceRef<'tcx>, - span: Span, + span: SpanId, flow_state: &Flows<'cx, 'tcx>, ) { // rust-lang/rust#21232: Until Rust allows reads from the @@ -1942,7 +1948,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { /// Returns `true` if an error is reported. fn check_access_permissions( &mut self, - (place, span): (Place<'tcx>, Span), + (place, span): (Place<'tcx>, SpanId), kind: ReadOrWrite, is_local_mutation_allowed: LocalMutationIsAllowed, flow_state: &Flows<'cx, 'tcx>, diff --git a/src/librustc_mir/borrow_check/region_infer/mod.rs b/src/librustc_mir/borrow_check/region_infer/mod.rs index fe11384380086..936747a25914f 100644 --- a/src/librustc_mir/borrow_check/region_infer/mod.rs +++ b/src/librustc_mir/borrow_check/region_infer/mod.rs @@ -15,7 +15,7 @@ use rustc_middle::mir::{ ConstraintCategory, Local, Location, }; use rustc_middle::ty::{self, subst::SubstsRef, RegionVid, Ty, TyCtxt, TypeFoldable}; -use rustc_span::Span; +use rustc_span::SpanId; use crate::borrow_check::{ constraints::{ @@ -80,9 +80,9 @@ pub struct RegionInferenceContext<'tcx> { /// `member_region_scc`. member_constraints_applied: Vec, - /// Map closure bounds to a `Span` that should be used for error reporting. + /// Map closure bounds to a `SpanId` that should be used for error reporting. closure_bounds_mapping: - FxHashMap>, + FxHashMap>, /// Contains the minimum universe of any variable within the same /// SCC. We will ensure that no SCC contains values that are not @@ -251,7 +251,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { member_constraints_in: MemberConstraintSet<'tcx, RegionVid>, closure_bounds_mapping: FxHashMap< Location, - FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>, + FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, SpanId)>, >, type_tests: Vec>, liveness_constraints: LivenessValues, @@ -1690,7 +1690,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { &self, body: &Body<'tcx>, constraint: &OutlivesConstraint, - ) -> (ConstraintCategory, bool, Span) { + ) -> (ConstraintCategory, bool, SpanId) { let loc = match constraint.locations { Locations::All(span) => return (constraint.category, false, span), Locations::Single(loc) => loc, @@ -1712,7 +1712,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { fr1: RegionVid, fr1_origin: NLLRegionVariableOrigin, fr2: RegionVid, - ) -> (ConstraintCategory, Span) { + ) -> (ConstraintCategory, SpanId) { let (category, _, span) = self.best_blame_constraint(body, fr1, fr1_origin, |r| { self.provides_universal_region(r, fr1, fr2) }); @@ -1906,7 +1906,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { from_region: RegionVid, from_region_origin: NLLRegionVariableOrigin, target_test: impl Fn(RegionVid) -> bool, - ) -> (ConstraintCategory, bool, Span) { + ) -> (ConstraintCategory, bool, SpanId) { debug!( "best_blame_constraint(from_region={:?}, from_region_origin={:?})", from_region, from_region_origin @@ -1928,7 +1928,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { ); // Classify each of the constraints along the path. - let mut categorized_path: Vec<(ConstraintCategory, bool, Span)> = path + let mut categorized_path: Vec<(ConstraintCategory, bool, SpanId)> = path .iter() .map(|constraint| { if constraint.category == ConstraintCategory::ClosureBounds { diff --git a/src/librustc_mir/borrow_check/region_infer/opaque_types.rs b/src/librustc_mir/borrow_check/region_infer/opaque_types.rs index 7e352bfba77bc..dd4b2d630a859 100644 --- a/src/librustc_mir/borrow_check/region_infer/opaque_types.rs +++ b/src/librustc_mir/borrow_check/region_infer/opaque_types.rs @@ -2,7 +2,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::DefId; use rustc_infer::infer::InferCtxt; use rustc_middle::ty::{self, TyCtxt, TypeFoldable}; -use rustc_span::Span; +use rustc_span::SpanId; use rustc_trait_selection::opaque_types::InferCtxtExt; use super::RegionInferenceContext; @@ -51,7 +51,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { &self, infcx: &InferCtxt<'_, 'tcx>, opaque_ty_decls: FxHashMap>, - span: Span, + span: SpanId, ) -> FxHashMap> { opaque_ty_decls .into_iter() @@ -119,7 +119,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { opaque_def_id, universal_substs, universal_concrete_type, - span, + infcx.tcx.reify_span(span), ); ( opaque_def_id, diff --git a/src/librustc_mir/borrow_check/type_check/free_region_relations.rs b/src/librustc_mir/borrow_check/type_check/free_region_relations.rs index f97dff146450c..826b229f5318a 100644 --- a/src/librustc_mir/borrow_check/type_check/free_region_relations.rs +++ b/src/librustc_mir/borrow_check/type_check/free_region_relations.rs @@ -8,7 +8,7 @@ use rustc_infer::infer::InferCtxt; use rustc_middle::mir::ConstraintCategory; use rustc_middle::traits::query::OutlivesBound; use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt}; -use rustc_span::DUMMY_SP; +use rustc_span::DUMMY_SPID; use rustc_trait_selection::traits::query::type_op::{self, TypeOp}; use std::rc::Rc; @@ -291,7 +291,7 @@ impl UniversalRegionRelationsBuilder<'cx, 'tcx> { &self.region_bound_pairs, self.implicit_region_bound, self.param_env, - Locations::All(DUMMY_SP), + Locations::All(DUMMY_SPID), ConstraintCategory::Internal, &mut self.constraints, ) diff --git a/src/librustc_mir/borrow_check/type_check/input_output.rs b/src/librustc_mir/borrow_check/type_check/input_output.rs index edd2dc3c2de55..7c5b24f95d386 100644 --- a/src/librustc_mir/borrow_check/type_check/input_output.rs +++ b/src/librustc_mir/borrow_check/type_check/input_output.rs @@ -12,7 +12,7 @@ use rustc_middle::mir::*; use rustc_middle::ty::Ty; use rustc_index::vec::Idx; -use rustc_span::Span; +use rustc_span::SpanId; use crate::borrow_check::universal_regions::UniversalRegions; @@ -41,12 +41,14 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { match typeck_tables.user_provided_sigs.get(&self.mir_def_id.to_def_id()) { None => None, Some(user_provided_poly_sig) => { + let body_span = self.tcx().reify_span(body.span); + // Instantiate the canonicalized variables from // user-provided signature (e.g., the `_` in the code // above) with fresh variables. let (poly_sig, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars( - body.span, + body_span, &user_provided_poly_sig, ); @@ -56,7 +58,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { Some( self.infcx .replace_bound_vars_with_fresh_vars( - body.span, + body_span, LateBoundRegionConversionTime::FnCall, &poly_sig, ) @@ -161,7 +163,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } } - fn equate_normalized_input_or_output(&mut self, a: Ty<'tcx>, b: Ty<'tcx>, span: Span) { + fn equate_normalized_input_or_output(&mut self, a: Ty<'tcx>, b: Ty<'tcx>, span: SpanId) { debug!("equate_normalized_input_or_output(a={:?}, b={:?})", a, b); if let Err(terr) = diff --git a/src/librustc_mir/borrow_check/type_check/liveness/trace.rs b/src/librustc_mir/borrow_check/type_check/liveness/trace.rs index f04736e04a053..c6d9e78ae068e 100644 --- a/src/librustc_mir/borrow_check/type_check/liveness/trace.rs +++ b/src/librustc_mir/borrow_check/type_check/liveness/trace.rs @@ -475,7 +475,10 @@ impl LivenessContext<'_, '_, '_, 'tcx> { drop_data.dropck_result.report_overflows( self.typeck.infcx.tcx, - self.body.source_info(*drop_locations.first().unwrap()).span, + self.typeck + .infcx + .tcx + .reify_span(self.body.source_info(*drop_locations.first().unwrap()).span), dropped_ty, ); diff --git a/src/librustc_mir/borrow_check/type_check/mod.rs b/src/librustc_mir/borrow_check/type_check/mod.rs index 9282a0a06b480..5ed68f465359a 100644 --- a/src/librustc_mir/borrow_check/type_check/mod.rs +++ b/src/librustc_mir/borrow_check/type_check/mod.rs @@ -29,7 +29,7 @@ use rustc_middle::ty::{ self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, RegionVid, ToPolyTraitRef, Ty, TyCtxt, UserType, UserTypeAnnotationIndex, }; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{SpanId, DUMMY_SPID}; use rustc_target::abi::VariantIdx; use rustc_trait_selection::infer::InferCtxtExt as _; use rustc_trait_selection::opaque_types::{GenerateMemberConstraints, InferCtxtExt}; @@ -246,7 +246,7 @@ fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) { } } -fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) { +fn mirbug(tcx: TyCtxt<'_>, span: SpanId, msg: &str) { // We sometimes see MIR failures (notably predicate failures) due to // the fact that we check rvalue sized predicates here. So use `delay_span_bug` // to avoid reporting bugs in those cases. @@ -266,13 +266,13 @@ struct TypeVerifier<'a, 'b, 'tcx> { cx: &'a mut TypeChecker<'b, 'tcx>, body: &'b Body<'tcx>, promoted: &'b IndexVec>, - last_span: Span, + last_span: SpanId, mir_def_id: LocalDefId, errors_reported: bool, } impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> { - fn visit_span(&mut self, span: &Span) { + fn visit_span(&mut self, span: &SpanId) { if !span.is_dummy() { self.last_span = *span; } @@ -806,7 +806,7 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { struct TypeChecker<'a, 'tcx> { infcx: &'a InferCtxt<'a, 'tcx>, param_env: ty::ParamEnv<'tcx>, - last_span: Span, + last_span: SpanId, body: &'a Body<'tcx>, /// User type annotations are shared between the main MIR and the MIR of /// all of the promoted items. @@ -814,7 +814,7 @@ struct TypeChecker<'a, 'tcx> { mir_def_id: LocalDefId, region_bound_pairs: &'a RegionBoundPairs<'tcx>, implicit_region_bound: ty::Region<'tcx>, - reported_errors: FxHashSet<(Ty<'tcx>, Span)>, + reported_errors: FxHashSet<(Ty<'tcx>, SpanId)>, borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>, universal_region_relations: &'a UniversalRegionRelations<'tcx>, opaque_type_values: FxHashMap>, @@ -865,7 +865,7 @@ crate struct MirTypeckRegionConstraints<'tcx> { crate member_constraints: MemberConstraintSet<'tcx, RegionVid>, crate closure_bounds_mapping: - FxHashMap>, + FxHashMap>, crate type_tests: Vec>, } @@ -929,8 +929,8 @@ pub enum Locations { /// /// The span points to the place the constraint arose. For example, /// it points to the type in a user-given type annotation. If - /// there's no sensible span then it's DUMMY_SP. - All(Span), + /// there's no sensible span then it's DUMMY_SPID. + All(SpanId), /// An outlives constraint that only has to hold at a single location, /// usually it represents a point where references flow from one spot to @@ -947,7 +947,7 @@ impl Locations { } /// Gets a span representing the location. - pub fn span(&self, body: &Body<'_>) -> Span { + pub fn span(&self, body: &Body<'_>) -> SpanId { match self { Locations::All(span) => *span, Locations::Single(l) => body.source_info(*l).span, @@ -968,7 +968,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { ) -> Self { let mut checker = Self { infcx, - last_span: DUMMY_SP, + last_span: DUMMY_SPID, mir_def_id, body, user_type_annotations: &body.user_type_annotations, @@ -994,6 +994,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation; let (annotation, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars(span, user_ty); + let span = span.into(); match annotation { UserType::Ty(mut ty) => { ty = self.normalize(ty, Locations::All(span)); @@ -1251,7 +1252,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { dummy_body_id, param_env, &anon_ty, - locations.span(body), + infcx.tcx.reify_span(locations.span(body)), )); debug!( "eq_opaque_type_and_type: \ @@ -1602,7 +1603,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } }; let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars( - term.source_info.span, + self.infcx.tcx.reify_span(term.source_info.span), LateBoundRegionConversionTime::FnCall, &sig, ); @@ -1892,7 +1893,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } } - fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) { + fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: SpanId) { let tcx = self.tcx(); // Erase the regions from `ty` to get a global type. The @@ -1987,7 +1988,11 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { // a required check to make sure that repeated elements implement `Copy`. let span = body.source_info(location).span; let ty = operand.ty(body, tcx); - if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) { + if !self.infcx.type_is_copy_modulo_regions( + self.param_env, + ty, + self.infcx.tcx.reify_span(span), + ) { let ccx = ConstCx::new_with_param_env( tcx, self.mir_def_id, @@ -2005,7 +2010,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { self.infcx.report_selection_error( &traits::Obligation::new( ObligationCause::new( - span, + self.infcx.tcx.reify_span(span), self.tcx().hir().local_def_id_to_hir_id(self.mir_def_id), traits::ObligationCauseCode::RepeatVec(should_suggest), ), @@ -2293,7 +2298,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let ty_right = right.ty(body, tcx); let common_ty = self.infcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, - span: body.source_info(location).span, + span: self.infcx.tcx.reify_span(body.source_info(location).span), }); self.relate_types( common_ty, diff --git a/src/librustc_mir/borrow_check/universal_regions.rs b/src/librustc_mir/borrow_check/universal_regions.rs index 3003f4639d9fa..dd6f9b46a75a5 100644 --- a/src/librustc_mir/borrow_check/universal_regions.rs +++ b/src/librustc_mir/borrow_check/universal_regions.rs @@ -457,7 +457,7 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { if self.infcx.tcx.fn_sig(def_id).c_variadic() { let va_list_did = self.infcx.tcx.require_lang_item( lang_items::VaListTypeLangItem, - Some(self.infcx.tcx.def_span(self.mir_def_id)), + Some(self.infcx.tcx.real_def_span(self.mir_def_id)), ); let region = self .infcx diff --git a/src/librustc_mir/const_eval/eval_queries.rs b/src/librustc_mir/const_eval/eval_queries.rs index b6c635fb22ab5..5973ed5324457 100644 --- a/src/librustc_mir/const_eval/eval_queries.rs +++ b/src/librustc_mir/const_eval/eval_queries.rs @@ -10,7 +10,7 @@ use rustc_middle::mir; use rustc_middle::mir::interpret::{ConstEvalErr, ErrorHandled}; use rustc_middle::traits::Reveal; use rustc_middle::ty::{self, subst::Subst, TyCtxt}; -use rustc_span::source_map::Span; +use rustc_span::source_map::SpanId; use rustc_target::abi::{Abi, LayoutOf}; use std::convert::TryInto; @@ -81,7 +81,7 @@ fn eval_body_using_ecx<'mir, 'tcx>( /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument. pub(super) fn mk_eval_cx<'mir, 'tcx>( tcx: TyCtxt<'tcx>, - span: Span, + span: SpanId, param_env: ty::ParamEnv<'tcx>, can_access_statics: bool, ) -> CompileTimeEvalContext<'mir, 'tcx> { diff --git a/src/librustc_mir/const_eval/mod.rs b/src/librustc_mir/const_eval/mod.rs index e1146ef30d131..da425d684f4d5 100644 --- a/src/librustc_mir/const_eval/mod.rs +++ b/src/librustc_mir/const_eval/mod.rs @@ -4,7 +4,7 @@ use std::convert::TryFrom; use rustc_middle::mir; use rustc_middle::ty::{self, TyCtxt}; -use rustc_span::{source_map::DUMMY_SP, symbol::Symbol}; +use rustc_span::{source_map::DUMMY_SPID, symbol::Symbol}; use rustc_target::abi::VariantIdx; use crate::interpret::{intern_const_alloc_recursive, ConstValue, InternKind, InterpCx}; @@ -30,7 +30,7 @@ pub(crate) fn const_field<'tcx>( value: &'tcx ty::Const<'tcx>, ) -> ConstValue<'tcx> { trace!("const_field: {:?}, {:?}", field, value); - let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false); + let ecx = mk_eval_cx(tcx, DUMMY_SPID, param_env, false); // get the operand again let op = ecx.eval_const_to_op(value, None).unwrap(); // downcast @@ -50,7 +50,7 @@ pub(crate) fn const_caller_location( (file, line, col): (Symbol, u32, u32), ) -> ConstValue<'tcx> { trace!("const_caller_location: {}:{}:{}", file, line, col); - let mut ecx = mk_eval_cx(tcx, DUMMY_SP, ty::ParamEnv::reveal_all(), false); + let mut ecx = mk_eval_cx(tcx, DUMMY_SPID, ty::ParamEnv::reveal_all(), false); let loc_place = ecx.alloc_caller_location(file, line, col); intern_const_alloc_recursive(&mut ecx, InternKind::Constant, loc_place, false).unwrap(); @@ -65,7 +65,7 @@ pub(crate) fn destructure_const<'tcx>( val: &'tcx ty::Const<'tcx>, ) -> mir::DestructuredConst<'tcx> { trace!("destructure_const: {:?}", val); - let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false); + let ecx = mk_eval_cx(tcx, DUMMY_SPID, param_env, false); let op = ecx.eval_const_to_op(val, None).unwrap(); let variant = ecx.read_discriminant(op).unwrap().1; diff --git a/src/librustc_mir/dataflow/framework/tests.rs b/src/librustc_mir/dataflow/framework/tests.rs index 3ed0a9594e7d5..aed4d16d8af5a 100644 --- a/src/librustc_mir/dataflow/framework/tests.rs +++ b/src/librustc_mir/dataflow/framework/tests.rs @@ -6,7 +6,7 @@ use rustc_index::bit_set::BitSet; use rustc_index::vec::IndexVec; use rustc_middle::mir::{self, BasicBlock, Location}; use rustc_middle::ty; -use rustc_span::DUMMY_SP; +use rustc_span::DUMMY_SPID; use super::*; use crate::dataflow::BottomValue; @@ -16,7 +16,7 @@ use crate::dataflow::BottomValue; /// This is the `Body` that will be used by the `MockAnalysis` below. The shape of its CFG is not /// important. fn mock_body() -> mir::Body<'static> { - let source_info = mir::SourceInfo::outermost(DUMMY_SP); + let source_info = mir::SourceInfo::outermost(DUMMY_SPID); let mut blocks = IndexVec::new(); let mut block = |n, kind| { diff --git a/src/librustc_mir/dataflow/impls/borrowed_locals.rs b/src/librustc_mir/dataflow/impls/borrowed_locals.rs index 6972a81cf1b0e..7842112081fd8 100644 --- a/src/librustc_mir/dataflow/impls/borrowed_locals.rs +++ b/src/librustc_mir/dataflow/impls/borrowed_locals.rs @@ -4,7 +4,7 @@ use crate::dataflow::{AnalysisDomain, GenKill, GenKillAnalysis}; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; use rustc_middle::ty::{ParamEnv, TyCtxt}; -use rustc_span::DUMMY_SP; +use rustc_span::DUMMY_SPID; pub type MaybeMutBorrowedLocals<'mir, 'tcx> = MaybeBorrowedLocals>; @@ -231,7 +231,7 @@ impl MutBorrow<'mir, 'tcx> { /// /// [rust-lang/unsafe-code-guidelines#134]: https://github.com/rust-lang/unsafe-code-guidelines/issues/134 fn shared_borrow_allows_mutation(&self, place: Place<'tcx>) -> bool { - !place.ty(self.body, self.tcx).ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) + !place.ty(self.body, self.tcx).ty.is_freeze(self.tcx, self.param_env, DUMMY_SPID) } } diff --git a/src/librustc_mir/dataflow/move_paths/mod.rs b/src/librustc_mir/dataflow/move_paths/mod.rs index d66d2625d78ea..6363056726f09 100644 --- a/src/librustc_mir/dataflow/move_paths/mod.rs +++ b/src/librustc_mir/dataflow/move_paths/mod.rs @@ -3,7 +3,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_index::vec::{Enumerated, IndexVec}; use rustc_middle::mir::*; use rustc_middle::ty::{ParamEnv, Ty, TyCtxt}; -use rustc_span::Span; +use rustc_span::SpanId; use smallvec::SmallVec; use std::fmt; @@ -277,7 +277,7 @@ impl fmt::Debug for Init { } impl Init { - crate fn span<'tcx>(&self, body: &Body<'tcx>) -> Span { + crate fn span<'tcx>(&self, body: &Body<'tcx>) -> SpanId { match self.location { InitLocation::Argument(local) => body.local_decls[local].source_info.span, InitLocation::Statement(location) => body.source_info(location).span, diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index 9bb7c879505f6..4ab48ce832860 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -17,7 +17,7 @@ use rustc_middle::ty::layout::{self, TyAndLayout}; use rustc_middle::ty::{ self, fold::BottomUpFolder, query::TyCtxtAt, subst::SubstsRef, Ty, TyCtxt, TypeFoldable, }; -use rustc_span::{source_map::DUMMY_SP, Span}; +use rustc_span::{SpanId, DUMMY_SPID}; use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Size, TargetDataLayout}; use super::{ @@ -307,7 +307,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } #[inline(always)] - pub fn set_span(&mut self, span: Span) { + pub fn set_span(&mut self, span: SpanId) { self.tcx.span = span; self.memory.tcx.span = span; } @@ -392,7 +392,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { #[inline] pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool { - ty.is_freeze(*self.tcx, self.param_env, DUMMY_SP) + ty.is_freeze(*self.tcx, self.param_env, DUMMY_SPID) } pub fn load_mir( @@ -948,7 +948,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { mir::ClearCrossCrate::Clear => None, } }); - let span = source_info.map_or(DUMMY_SP, |source_info| source_info.span); + let span = source_info.map_or(DUMMY_SPID, |source_info| source_info.span).into(); frames.push(FrameInfo { span, instance: frame.instance, lint_root }); } diff --git a/src/librustc_mir/interpret/intern.rs b/src/librustc_mir/interpret/intern.rs index 1c44101595d4f..4aa2c6ec65f9f 100644 --- a/src/librustc_mir/interpret/intern.rs +++ b/src/librustc_mir/interpret/intern.rs @@ -207,7 +207,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx>> ValueVisitor<'mir self.intern_shallow(vtable.alloc_id, Mutability::Not, None)?; } else { self.ecx().tcx.sess.delay_span_bug( - rustc_span::DUMMY_SP, + rustc_span::DUMMY_SPID, "vtables pointers cannot be integer pointers", ); } diff --git a/src/librustc_mir/interpret/intrinsics/caller_location.rs b/src/librustc_mir/interpret/intrinsics/caller_location.rs index 91b046d7bb264..f162a5f07d8a2 100644 --- a/src/librustc_mir/interpret/intrinsics/caller_location.rs +++ b/src/librustc_mir/interpret/intrinsics/caller_location.rs @@ -2,7 +2,7 @@ use std::convert::TryFrom; use rustc_hir::lang_items::PanicLocationLangItem; use rustc_middle::ty::subst::Subst; -use rustc_span::{Span, Symbol}; +use rustc_span::{SpanId, Symbol}; use rustc_target::abi::LayoutOf; use crate::interpret::{ @@ -13,7 +13,7 @@ use crate::interpret::{ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { /// Walks up the callstack from the intrinsic's callsite, searching for the first callsite in a /// frame which is not `#[track_caller]`. - crate fn find_closest_untracked_caller_location(&self) -> Span { + crate fn find_closest_untracked_caller_location(&self) -> SpanId { self.stack() .iter() .rev() @@ -59,7 +59,8 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { location } - crate fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) { + crate fn location_triple_for_span(&self, span: SpanId) -> (Symbol, u32, u32) { + let span = self.tcx.reify_span(span); let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span); let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo()); ( @@ -69,7 +70,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { ) } - pub fn alloc_caller_location_for_span(&mut self, span: Span) -> MPlaceTy<'tcx, M::PointerTag> { + pub fn alloc_caller_location_for_span( + &mut self, + span: SpanId, + ) -> MPlaceTy<'tcx, M::PointerTag> { let (file, line, column) = self.location_triple_for_span(span); self.alloc_caller_location(file, line, column) } diff --git a/src/librustc_mir/interpret/step.rs b/src/librustc_mir/interpret/step.rs index bb4c0156c88cf..c74ad96eb5c9f 100644 --- a/src/librustc_mir/interpret/step.rs +++ b/src/librustc_mir/interpret/step.rs @@ -76,7 +76,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> InterpResult<'tcx> { info!("{:?}", stmt); - self.set_span(stmt.source_info.span); + self.set_span(stmt.source_info.span.into()); use rustc_middle::mir::StatementKind::*; @@ -273,7 +273,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { fn terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> InterpResult<'tcx> { info!("{:?}", terminator.kind); - self.set_span(terminator.source_info.span); + self.set_span(terminator.source_info.span.into()); self.eval_terminator(terminator)?; if !self.stack().is_empty() { diff --git a/src/librustc_mir/monomorphize/collector.rs b/src/librustc_mir/monomorphize/collector.rs index 4648100e3b701..5b2b3be2ade7b 100644 --- a/src/librustc_mir/monomorphize/collector.rs +++ b/src/librustc_mir/monomorphize/collector.rs @@ -809,8 +809,8 @@ fn find_vtable_types_for_unsizing<'tcx>( let ptr_vtable = |inner_source: Ty<'tcx>, inner_target: Ty<'tcx>| { let param_env = ty::ParamEnv::reveal_all(); let type_has_metadata = |ty: Ty<'tcx>| -> bool { - use rustc_span::DUMMY_SP; - if ty.is_sized(tcx.at(DUMMY_SP), param_env) { + use rustc_span::DUMMY_SPID; + if ty.is_sized(tcx.at(DUMMY_SPID), param_env) { return false; } let tail = tcx.struct_tail_erasing_lifetimes(ty, param_env); diff --git a/src/librustc_mir/monomorphize/partitioning.rs b/src/librustc_mir/monomorphize/partitioning.rs index db1ea72c0a531..7009068cfbcad 100644 --- a/src/librustc_mir/monomorphize/partitioning.rs +++ b/src/librustc_mir/monomorphize/partitioning.rs @@ -870,7 +870,11 @@ where // Deterministically select one of the spans for error reporting let span = match (span1, span2) { (Some(span1), Some(span2)) => { - Some(if span1.lo().0 > span2.lo().0 { span1 } else { span2 }) + Some(if tcx.reify_span(span1).lo().0 > tcx.reify_span(span2).lo().0 { + span1 + } else { + span2 + }) } (span1, span2) => span1.or(span2), }; diff --git a/src/librustc_mir/shim.rs b/src/librustc_mir/shim.rs index 847f59b95e959..3bdb2fb8fb782 100644 --- a/src/librustc_mir/shim.rs +++ b/src/librustc_mir/shim.rs @@ -8,7 +8,7 @@ use rustc_target::abi::VariantIdx; use rustc_index::vec::{Idx, IndexVec}; -use rustc_span::Span; +use rustc_span::SpanId; use rustc_target::spec::abi::Abi; use std::fmt; @@ -147,7 +147,7 @@ enum CallKind { fn local_decls_for_sig<'tcx>( sig: &ty::FnSig<'tcx>, - span: Span, + span: SpanId, ) -> IndexVec> { iter::once(LocalDecl::new(sig.output(), span)) .chain(sig.inputs().iter().map(|ity| LocalDecl::new(ity, span).immutable())) @@ -228,7 +228,7 @@ fn new_body<'tcx>( basic_blocks: IndexVec>, local_decls: IndexVec>, arg_count: usize, - span: Span, + span: SpanId, ) -> Body<'tcx> { Body::new( basic_blocks, @@ -306,7 +306,7 @@ fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) - let param_env = tcx.param_env(def_id); let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty); - let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env, builder.span); + let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env, builder.span.into()); let dest = Place::return_place(); let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0))); @@ -332,7 +332,7 @@ struct CloneShimBuilder<'tcx> { def_id: DefId, local_decls: IndexVec>, blocks: IndexVec>, - span: Span, + span: SpanId, sig: ty::FnSig<'tcx>, } @@ -826,6 +826,7 @@ pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> { let span = tcx.hir().span_if_local(ctor_id).unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id)); + let span = span.into(); let param_env = tcx.param_env(ctor_id); diff --git a/src/librustc_mir/transform/check_consts/ops.rs b/src/librustc_mir/transform/check_consts/ops.rs index 28743ee8e3636..c1e5f4bb19b22 100644 --- a/src/librustc_mir/transform/check_consts/ops.rs +++ b/src/librustc_mir/transform/check_consts/ops.rs @@ -6,7 +6,7 @@ use rustc_hir::def_id::DefId; use rustc_session::config::nightly_options; use rustc_session::parse::feature_err; use rustc_span::symbol::sym; -use rustc_span::{Span, Symbol}; +use rustc_span::{SpanId, Symbol}; use super::ConstCx; @@ -32,7 +32,7 @@ pub trait NonConstOp: std::fmt::Debug { Self::feature_gate().map_or(false, |gate| ccx.tcx.features().enabled(gate)) } - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { let mut err = struct_span_err!( ccx.tcx.sess, span, @@ -61,7 +61,7 @@ pub trait NonConstOp: std::fmt::Debug { #[derive(Debug)] pub struct FnCallIndirect; impl NonConstOp for FnCallIndirect { - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { let mut err = ccx.tcx.sess.struct_span_err(span, "function pointers are not allowed in const fn"); err.emit(); @@ -72,7 +72,7 @@ impl NonConstOp for FnCallIndirect { #[derive(Debug)] pub struct FnCallNonConst(pub DefId); impl NonConstOp for FnCallNonConst { - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { let mut err = struct_span_err!( ccx.tcx.sess, span, @@ -91,7 +91,7 @@ impl NonConstOp for FnCallNonConst { #[derive(Debug)] pub struct FnCallUnstable(pub DefId, pub Symbol); impl NonConstOp for FnCallUnstable { - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { let FnCallUnstable(def_id, feature) = *self; let mut err = ccx.tcx.sess.struct_span_err( @@ -108,7 +108,7 @@ impl NonConstOp for FnCallUnstable { #[derive(Debug)] pub struct HeapAllocation; impl NonConstOp for HeapAllocation { - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { let mut err = struct_span_err!( ccx.tcx.sess, span, @@ -136,7 +136,7 @@ impl NonConstOp for IfOrMatch { Some(sym::const_if_match) } - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { // This should be caught by the HIR const-checker. ccx.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context"); } @@ -149,7 +149,7 @@ impl NonConstOp for InlineAsm {} #[derive(Debug)] pub struct LiveDrop; impl NonConstOp for LiveDrop { - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { struct_span_err!( ccx.tcx.sess, span, @@ -168,7 +168,7 @@ impl NonConstOp for Loop { Some(sym::const_loop) } - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { // This should be caught by the HIR const-checker. ccx.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context"); } @@ -177,7 +177,7 @@ impl NonConstOp for Loop { #[derive(Debug)] pub struct CellBorrow; impl NonConstOp for CellBorrow { - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { struct_span_err!( ccx.tcx.sess, span, @@ -196,7 +196,7 @@ impl NonConstOp for MutBorrow { Some(sym::const_mut_refs) } - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { let mut err = feature_err( &ccx.tcx.sess.parse_sess, sym::const_mut_refs, @@ -231,7 +231,7 @@ impl NonConstOp for MutAddressOf { Some(sym::const_mut_refs) } - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { feature_err( &ccx.tcx.sess.parse_sess, sym::const_mut_refs, @@ -257,7 +257,7 @@ impl NonConstOp for Panic { Some(sym::const_panic) } - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { feature_err( &ccx.tcx.sess.parse_sess, sym::const_panic, @@ -275,7 +275,7 @@ impl NonConstOp for RawPtrComparison { Some(sym::const_compare_raw_pointers) } - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { feature_err( &ccx.tcx.sess.parse_sess, sym::const_compare_raw_pointers, @@ -293,7 +293,7 @@ impl NonConstOp for RawPtrDeref { Some(sym::const_raw_ptr_deref) } - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { feature_err( &ccx.tcx.sess.parse_sess, sym::const_raw_ptr_deref, @@ -311,7 +311,7 @@ impl NonConstOp for RawPtrToIntCast { Some(sym::const_raw_ptr_to_usize_cast) } - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { feature_err( &ccx.tcx.sess.parse_sess, sym::const_raw_ptr_to_usize_cast, @@ -330,7 +330,7 @@ impl NonConstOp for StaticAccess { matches!(ccx.const_kind(), hir::ConstContext::Static(_)) } - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { let mut err = struct_span_err!( ccx.tcx.sess, span, @@ -358,7 +358,7 @@ pub struct ThreadLocalAccess; impl NonConstOp for ThreadLocalAccess { const IS_SUPPORTED_IN_MIRI: bool = false; - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { struct_span_err!( ccx.tcx.sess, span, @@ -383,7 +383,7 @@ impl NonConstOp for UnionAccess { Some(sym::const_fn_union) } - fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: SpanId) { feature_err( &ccx.tcx.sess.parse_sess, sym::const_fn_union, diff --git a/src/librustc_mir/transform/check_consts/qualifs.rs b/src/librustc_mir/transform/check_consts/qualifs.rs index fc6860b40e8d2..310dcf6b51ec0 100644 --- a/src/librustc_mir/transform/check_consts/qualifs.rs +++ b/src/librustc_mir/transform/check_consts/qualifs.rs @@ -5,7 +5,7 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::mir::*; use rustc_middle::ty::{self, subst::SubstsRef, AdtDef, Ty}; -use rustc_span::DUMMY_SP; +use rustc_span::DUMMY_SPID; use rustc_trait_selection::traits; use super::ConstCx; @@ -78,7 +78,7 @@ impl Qualif for HasMutInterior { } fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { - !ty.is_freeze(cx.tcx, cx.param_env, DUMMY_SP) + !ty.is_freeze(cx.tcx, cx.param_env, DUMMY_SPID) } fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool { @@ -128,7 +128,13 @@ impl Qualif for CustomEq { // `Option::::Some`), in which case some values of this type may be // structural-match (`Option::None`). let id = cx.tcx.hir().local_def_id_to_hir_id(cx.def_id.as_local().unwrap()); - traits::search_for_structural_match_violation(id, cx.body.span, cx.tcx, ty).is_some() + traits::search_for_structural_match_violation( + id, + cx.tcx.reify_span(cx.body.span), + cx.tcx, + ty, + ) + .is_some() } fn in_adt_inherently( @@ -138,9 +144,9 @@ impl Qualif for CustomEq { ) -> bool { let ty = cx.tcx.mk_ty(ty::Adt(adt, substs)); let id = cx.tcx.hir().local_def_id_to_hir_id(cx.def_id.as_local().unwrap()); - cx.tcx - .infer_ctxt() - .enter(|infcx| !traits::type_marked_structural(id, cx.body.span, &infcx, ty)) + cx.tcx.infer_ctxt().enter(|infcx| { + !traits::type_marked_structural(id, cx.tcx.reify_span(cx.body.span), &infcx, ty) + }) } } diff --git a/src/librustc_mir/transform/check_consts/validation.rs b/src/librustc_mir/transform/check_consts/validation.rs index 8c005fdcdbf77..cd8eb6c8487e8 100644 --- a/src/librustc_mir/transform/check_consts/validation.rs +++ b/src/librustc_mir/transform/check_consts/validation.rs @@ -8,7 +8,7 @@ use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceC use rustc_middle::mir::*; use rustc_middle::ty::cast::CastTy; use rustc_middle::ty::{self, Instance, InstanceDef, TyCtxt}; -use rustc_span::Span; +use rustc_span::SpanId; use rustc_trait_selection::traits::error_reporting::InferCtxtExt; use rustc_trait_selection::traits::{self, TraitEngine}; @@ -175,7 +175,7 @@ pub struct Validator<'mir, 'tcx> { qualifs: Qualifs<'mir, 'tcx>, /// The span of the current statement. - span: Span, + span: SpanId, } impl Deref for Validator<'mir, 'tcx> { @@ -234,7 +234,7 @@ impl Validator<'mir, 'tcx> { /// Emits an error at the given `span` if an expression cannot be evaluated in the current /// context. - pub fn check_op_spanned(&mut self, op: O, span: Span) + pub fn check_op_spanned(&mut self, op: O, span: SpanId) where O: NonConstOp, { @@ -249,7 +249,7 @@ impl Validator<'mir, 'tcx> { let is_unleashable = O::IS_SUPPORTED_IN_MIRI; if is_unleashable && self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you { - self.tcx.sess.miri_unleashed_feature(span, O::feature_gate()); + self.tcx.sess.miri_unleashed_feature(self.tcx.reify_span(span), O::feature_gate()); return; } @@ -262,7 +262,7 @@ impl Validator<'mir, 'tcx> { self.check_op_spanned(op, span) } - fn check_static(&mut self, def_id: DefId, span: Span) { + fn check_static(&mut self, def_id: DefId, span: SpanId) { if self.tcx.is_thread_local_static(def_id) { self.check_op_spanned(ops::ThreadLocalAccess, span) } else { @@ -567,7 +567,7 @@ impl Visitor<'tcx> for Validator<'mir, 'tcx> { } else if let Some(feature) = is_unstable_const_fn(self.tcx, def_id) { // Exempt unstable const fns inside of macros with // `#[allow_internal_unstable]`. - if !self.span.allows_unstable(feature) { + if !self.tcx.reify_span(self.span).allows_unstable(feature) { self.check_op(ops::FnCallUnstable(def_id, feature)); } } else { @@ -620,7 +620,7 @@ impl Visitor<'tcx> for Validator<'mir, 'tcx> { } } -fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) { +fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: SpanId, msg: Cow<'_, str>) { struct_span_err!(tcx.sess, span, E0723, "{}", msg) .note( "see issue #57563 \ @@ -671,9 +671,10 @@ fn check_short_circuiting_in_const_local(ccx: &ConstCx<'_, 'tcx>) { fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) { let ty = body.return_ty(); tcx.infer_ctxt().enter(|infcx| { - let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic); + let body_span = tcx.reify_span(body.span); + let cause = traits::ObligationCause::new(body_span, hir_id, traits::SharedStatic); let mut fulfillment_cx = traits::FulfillmentContext::new(); - let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span)); + let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body_span)); fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause); if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) { infcx.report_fulfillment_errors(&err, None, false); diff --git a/src/librustc_mir/transform/check_unsafety.rs b/src/librustc_mir/transform/check_unsafety.rs index 0bd9b3e1b2084..b4e66663ac30d 100644 --- a/src/librustc_mir/transform/check_unsafety.rs +++ b/src/librustc_mir/transform/check_unsafety.rs @@ -271,7 +271,7 @@ impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> { if !elem_ty.is_copy_modulo_regions( self.tcx, self.param_env, - self.source_info.span, + self.source_info.span.into(), ) { self.require_unsafe( "assignment to non-`Copy` union field", @@ -419,7 +419,7 @@ impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> { } else if !place.ty(self.body, self.tcx).ty.is_freeze( self.tcx, self.param_env, - self.source_info.span, + self.source_info.span.into(), ) { ( "borrow of layout constrained field with interior \ diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index e898f22ec230d..f3e31dc71d05e 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -21,7 +21,7 @@ use rustc_middle::ty::layout::{HasTyCtxt, LayoutError, TyAndLayout}; use rustc_middle::ty::subst::{InternalSubsts, Subst}; use rustc_middle::ty::{self, ConstKind, Instance, ParamEnv, Ty, TyCtxt, TypeFoldable}; use rustc_session::lint; -use rustc_span::{def_id::DefId, Span}; +use rustc_span::{def_id::DefId, SpanId}; use rustc_target::abi::{HasDataLayout, LayoutOf, Size, TargetDataLayout}; use rustc_trait_selection::traits; @@ -405,7 +405,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { Ok(op) => Some(op), Err(error) => { // Make sure errors point at the constant. - self.ecx.set_span(c.span); + self.ecx.set_span(c.span.into()); let err = error_to_const_error(&self.ecx, error); if let Some(lint_root) = self.lint_root(source_info) { let lint_only = match c.literal.val { @@ -602,7 +602,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { } /// Creates a new `Operand::Constant` from a `Scalar` value - fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> { + fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: SpanId) -> Operand<'tcx> { Operand::Constant(Box::new(Constant { span, user_ty: None, @@ -827,7 +827,7 @@ impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> { fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) { trace!("visit_statement: {:?}", statement); let source_info = statement.source_info; - self.ecx.set_span(source_info.span); + self.ecx.set_span(source_info.span.into()); self.source_info = Some(source_info); if let StatementKind::Assign(box (place, ref mut rval)) = statement.kind { let place_ty: Ty<'tcx> = place.ty(&self.local_decls, self.tcx).ty; @@ -898,7 +898,7 @@ impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> { fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) { let source_info = terminator.source_info; - self.ecx.set_span(source_info.span); + self.ecx.set_span(source_info.span.into()); self.source_info = Some(source_info); self.super_terminator(terminator, location); match &mut terminator.kind { diff --git a/src/librustc_mir/transform/elaborate_drops.rs b/src/librustc_mir/transform/elaborate_drops.rs index e379e5ee656b7..ae71187f11fb9 100644 --- a/src/librustc_mir/transform/elaborate_drops.rs +++ b/src/librustc_mir/transform/elaborate_drops.rs @@ -14,7 +14,7 @@ use rustc_hir as hir; use rustc_index::bit_set::BitSet; use rustc_middle::mir::*; use rustc_middle::ty::{self, TyCtxt}; -use rustc_span::Span; +use rustc_span::SpanId; use rustc_target::abi::VariantIdx; use std::fmt; @@ -265,7 +265,7 @@ impl<'b, 'tcx> ElaborateDropsCtxt<'b, 'tcx> { self.env.param_env } - fn create_drop_flag(&mut self, index: MovePathIndex, span: Span) { + fn create_drop_flag(&mut self, index: MovePathIndex, span: SpanId) { let tcx = self.tcx; let patch = &mut self.patch; debug!("create_drop_flag({:?})", self.body.span); @@ -465,7 +465,7 @@ impl<'b, 'tcx> ElaborateDropsCtxt<'b, 'tcx> { } } - fn constant_bool(&self, span: Span, val: bool) -> Rvalue<'tcx> { + fn constant_bool(&self, span: SpanId, val: bool) -> Rvalue<'tcx> { Rvalue::Use(Operand::Constant(Box::new(Constant { span, user_ty: None, diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs index 6dade3c8dca6c..e2529eb99e49e 100644 --- a/src/librustc_mir/transform/promote_consts.rs +++ b/src/librustc_mir/transform/promote_consts.rs @@ -22,7 +22,7 @@ use rustc_middle::ty::cast::CastTy; use rustc_middle::ty::subst::InternalSubsts; use rustc_middle::ty::{self, List, TyCtxt, TypeFoldable}; use rustc_span::symbol::sym; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{SpanId, DUMMY_SPID}; use rustc_index::vec::{Idx, IndexVec}; use rustc_target::spec::abi::Abi; @@ -144,7 +144,7 @@ struct Collector<'a, 'tcx> { ccx: &'a ConstCx<'a, 'tcx>, temps: IndexVec, candidates: Vec, - span: Span, + span: SpanId, } impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> { @@ -330,7 +330,7 @@ impl<'tcx> Validator<'_, 'tcx> { Place::ty_from(place.local, proj_base, self.body, self.tcx) .projection_ty(self.tcx, elem) .ty; - if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) { + if ty.is_freeze(self.tcx, self.param_env, DUMMY_SPID) { has_mut_interior = false; break; } @@ -653,7 +653,7 @@ impl<'tcx> Validator<'_, 'tcx> { let ty = Place::ty_from(place.local, proj_base, self.body, self.tcx) .projection_ty(self.tcx, elem) .ty; - if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) { + if ty.is_freeze(self.tcx, self.param_env, DUMMY_SPID) { has_mut_interior = false; break; } @@ -785,7 +785,7 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> { }) } - fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) { + fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: SpanId) { let last = self.promoted.basic_blocks().last().unwrap(); let data = &mut self.promoted[last]; data.statements.push(Statement { diff --git a/src/librustc_mir/transform/qualify_min_const_fn.rs b/src/librustc_mir/transform/qualify_min_const_fn.rs index c9982aeaa0839..ef11d23350443 100644 --- a/src/librustc_mir/transform/qualify_min_const_fn.rs +++ b/src/librustc_mir/transform/qualify_min_const_fn.rs @@ -5,10 +5,10 @@ use rustc_middle::mir::*; use rustc_middle::ty::subst::GenericArgKind; use rustc_middle::ty::{self, adjustment::PointerCast, Predicate, Ty, TyCtxt}; use rustc_span::symbol::{sym, Symbol}; -use rustc_span::Span; +use rustc_span::SpanId; use std::borrow::Cow; -type McfResult = Result<(), (Span, Cow<'static, str>)>; +type McfResult = Result<(), (SpanId, Cow<'static, str>)>; pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'a Body<'tcx>) -> McfResult { // Prevent const trait methods from being annotated as `stable`. @@ -92,7 +92,7 @@ pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'a Body<'tcx>) - Ok(()) } -fn check_ty(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span, fn_def_id: DefId) -> McfResult { +fn check_ty(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: SpanId, fn_def_id: DefId) -> McfResult { for arg in ty.walk() { let ty = match arg.unpack() { GenericArgKind::Type(ty) => ty, @@ -150,7 +150,7 @@ fn check_rvalue( body: &Body<'tcx>, def_id: DefId, rvalue: &Rvalue<'tcx>, - span: Span, + span: SpanId, ) -> McfResult { match rvalue { Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => { @@ -262,7 +262,7 @@ fn check_statement( fn check_operand( tcx: TyCtxt<'tcx>, operand: &Operand<'tcx>, - span: Span, + span: SpanId, def_id: DefId, body: &Body<'tcx>, ) -> McfResult { @@ -278,7 +278,7 @@ fn check_operand( fn check_place( tcx: TyCtxt<'tcx>, place: Place<'tcx>, - span: Span, + span: SpanId, def_id: DefId, body: &Body<'tcx>, ) -> McfResult { diff --git a/src/librustc_mir/transform/rustc_peek.rs b/src/librustc_mir/transform/rustc_peek.rs index 5eb374e7ee2f1..dea86d4989f16 100644 --- a/src/librustc_mir/transform/rustc_peek.rs +++ b/src/librustc_mir/transform/rustc_peek.rs @@ -1,6 +1,6 @@ use rustc_ast::ast; use rustc_span::symbol::sym; -use rustc_span::Span; +use rustc_span::SpanId; use rustc_target::spec::abi::Abi; use crate::transform::{MirPass, MirSource}; @@ -190,7 +190,7 @@ impl PeekCallKind { pub struct PeekCall { arg: Local, kind: PeekCallKind, - span: Span, + span: SpanId, } impl PeekCall { diff --git a/src/librustc_mir/util/borrowck_errors.rs b/src/librustc_mir/util/borrowck_errors.rs index f8bb7e7a85d11..963d094935d7d 100644 --- a/src/librustc_mir/util/borrowck_errors.rs +++ b/src/librustc_mir/util/borrowck_errors.rs @@ -1,17 +1,17 @@ use rustc_errors::{struct_span_err, DiagnosticBuilder, DiagnosticId}; use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_span::{MultiSpan, Span}; +use rustc_span::{MultiSpanId, SpanId}; impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { - crate fn cannot_move_when_borrowed(&self, span: Span, desc: &str) -> DiagnosticBuilder<'cx> { + crate fn cannot_move_when_borrowed(&self, span: SpanId, desc: &str) -> DiagnosticBuilder<'cx> { struct_span_err!(self, span, E0505, "cannot move out of {} because it is borrowed", desc,) } crate fn cannot_use_when_mutably_borrowed( &self, - span: Span, + span: SpanId, desc: &str, - borrow_span: Span, + borrow_span: SpanId, borrow_desc: &str, ) -> DiagnosticBuilder<'cx> { let mut err = struct_span_err!( @@ -29,7 +29,7 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_act_on_uninitialized_variable( &self, - span: Span, + span: SpanId, verb: &str, desc: &str, ) -> DiagnosticBuilder<'cx> { @@ -45,12 +45,12 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_mutably_borrow_multiply( &self, - new_loan_span: Span, + new_loan_span: SpanId, desc: &str, opt_via: &str, - old_loan_span: Span, + old_loan_span: SpanId, old_opt_via: &str, - old_load_end_span: Option, + old_load_end_span: Option, ) -> DiagnosticBuilder<'cx> { let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {})", msg) }; @@ -94,10 +94,10 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_uniquely_borrow_by_two_closures( &self, - new_loan_span: Span, + new_loan_span: SpanId, desc: &str, - old_loan_span: Span, - old_load_end_span: Option, + old_loan_span: SpanId, + old_load_end_span: Option, ) -> DiagnosticBuilder<'cx> { let mut err = struct_span_err!( self, @@ -123,14 +123,14 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_uniquely_borrow_by_one_closure( &self, - new_loan_span: Span, + new_loan_span: SpanId, container_name: &str, desc_new: &str, opt_via: &str, - old_loan_span: Span, + old_loan_span: SpanId, noun_old: &str, old_opt_via: &str, - previous_end_span: Option, + previous_end_span: Option, ) -> DiagnosticBuilder<'cx> { let mut err = struct_span_err!( self, @@ -154,14 +154,14 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_reborrow_already_uniquely_borrowed( &self, - new_loan_span: Span, + new_loan_span: SpanId, container_name: &str, desc_new: &str, opt_via: &str, kind_new: &str, - old_loan_span: Span, + old_loan_span: SpanId, old_opt_via: &str, - previous_end_span: Option, + previous_end_span: Option, second_borrow_desc: &str, ) -> DiagnosticBuilder<'cx> { let mut err = struct_span_err!( @@ -190,15 +190,15 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_reborrow_already_borrowed( &self, - span: Span, + span: SpanId, desc_new: &str, msg_new: &str, kind_new: &str, - old_span: Span, + old_span: SpanId, noun_old: &str, kind_old: &str, msg_old: &str, - old_load_end_span: Option, + old_load_end_span: Option, ) -> DiagnosticBuilder<'cx> { let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {})", msg) }; @@ -239,8 +239,8 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_assign_to_borrowed( &self, - span: Span, - borrow_span: Span, + span: SpanId, + borrow_span: SpanId, desc: &str, ) -> DiagnosticBuilder<'cx> { let mut err = struct_span_err!( @@ -258,7 +258,7 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_reassign_immutable( &self, - span: Span, + span: SpanId, desc: &str, is_arg: bool, ) -> DiagnosticBuilder<'cx> { @@ -266,13 +266,13 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { struct_span_err!(self, span, E0384, "cannot assign {} {}", msg, desc) } - crate fn cannot_assign(&self, span: Span, desc: &str) -> DiagnosticBuilder<'cx> { + crate fn cannot_assign(&self, span: SpanId, desc: &str) -> DiagnosticBuilder<'cx> { struct_span_err!(self, span, E0594, "cannot assign to {}", desc) } crate fn cannot_move_out_of( &self, - move_from_span: Span, + move_from_span: SpanId, move_from_desc: &str, ) -> DiagnosticBuilder<'cx> { struct_span_err!(self, move_from_span, E0507, "cannot move out of {}", move_from_desc,) @@ -283,7 +283,7 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { /// didn't capture whether there was an indexing operation or not. crate fn cannot_move_out_of_interior_noncopy( &self, - move_from_span: Span, + move_from_span: SpanId, ty: Ty<'_>, is_index: Option, ) -> DiagnosticBuilder<'cx> { @@ -306,7 +306,7 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_move_out_of_interior_of_drop( &self, - move_from_span: Span, + move_from_span: SpanId, container_ty: Ty<'_>, ) -> DiagnosticBuilder<'cx> { let mut err = struct_span_err!( @@ -322,7 +322,7 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_act_on_moved_value( &self, - use_span: Span, + use_span: SpanId, verb: &str, optional_adverb_for_moved: &str, moved_path: Option, @@ -342,7 +342,7 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_borrow_path_as_mutable_because( &self, - span: Span, + span: SpanId, path: &str, reason: &str, ) -> DiagnosticBuilder<'cx> { @@ -351,8 +351,8 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_mutate_in_immutable_section( &self, - mutate_span: Span, - immutable_span: Span, + mutate_span: SpanId, + immutable_span: SpanId, immutable_place: &str, immutable_section: &str, action: &str, @@ -373,8 +373,8 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_borrow_across_generator_yield( &self, - span: Span, - yield_span: Span, + span: SpanId, + yield_span: SpanId, ) -> DiagnosticBuilder<'cx> { let mut err = struct_span_err!( self, @@ -386,7 +386,7 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { err } - crate fn cannot_borrow_across_destructor(&self, borrow_span: Span) -> DiagnosticBuilder<'cx> { + crate fn cannot_borrow_across_destructor(&self, borrow_span: SpanId) -> DiagnosticBuilder<'cx> { struct_span_err!( self, borrow_span, @@ -397,7 +397,7 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn path_does_not_live_long_enough( &self, - span: Span, + span: SpanId, path: &str, ) -> DiagnosticBuilder<'cx> { struct_span_err!(self, span, E0597, "{} does not live long enough", path,) @@ -405,7 +405,7 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_return_reference_to_local( &self, - span: Span, + span: SpanId, return_kind: &str, reference_desc: &str, path_desc: &str, @@ -430,10 +430,10 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn cannot_capture_in_long_lived_closure( &self, - closure_span: Span, + closure_span: SpanId, closure_kind: &str, borrowed_path: &str, - capture_span: Span, + capture_span: SpanId, ) -> DiagnosticBuilder<'cx> { let mut err = struct_span_err!( self, @@ -452,16 +452,16 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn thread_local_value_does_not_live_long_enough( &self, - span: Span, + span: SpanId, ) -> DiagnosticBuilder<'cx> { struct_span_err!(self, span, E0712, "thread-local variable borrowed past end of function",) } - crate fn temporary_value_borrowed_for_too_long(&self, span: Span) -> DiagnosticBuilder<'cx> { + crate fn temporary_value_borrowed_for_too_long(&self, span: SpanId) -> DiagnosticBuilder<'cx> { struct_span_err!(self, span, E0716, "temporary value dropped while borrowed",) } - fn struct_span_err_with_code>( + fn struct_span_err_with_code>( &self, sp: S, msg: &str, @@ -473,7 +473,7 @@ impl<'cx, 'tcx> crate::borrow_check::MirBorrowckCtxt<'cx, 'tcx> { crate fn borrowed_data_escapes_closure<'tcx>( tcx: TyCtxt<'tcx>, - escape_span: Span, + escape_span: SpanId, escapes_from: &str, ) -> DiagnosticBuilder<'tcx> { struct_span_err!( diff --git a/src/librustc_mir/util/elaborate_drops.rs b/src/librustc_mir/util/elaborate_drops.rs index 2d7d3a0ccae14..1c87318327a9d 100644 --- a/src/librustc_mir/util/elaborate_drops.rs +++ b/src/librustc_mir/util/elaborate_drops.rs @@ -877,8 +877,10 @@ where ) -> BasicBlock { let tcx = self.tcx(); let unit_temp = Place::from(self.new_temp(tcx.mk_unit())); - let free_func = - tcx.require_lang_item(lang_items::BoxFreeFnLangItem, Some(self.source_info.span)); + let free_func = tcx.require_lang_item( + lang_items::BoxFreeFnLangItem, + Some(tcx.reify_span(self.source_info.span)), + ); let args = adt.variants[VariantIdx::new(0)] .fields .iter() diff --git a/src/librustc_mir/util/patch.rs b/src/librustc_mir/util/patch.rs index 6566a996fe442..4087265164381 100644 --- a/src/librustc_mir/util/patch.rs +++ b/src/librustc_mir/util/patch.rs @@ -1,7 +1,7 @@ use rustc_index::vec::{Idx, IndexVec}; use rustc_middle::mir::*; use rustc_middle::ty::Ty; -use rustc_span::Span; +use rustc_span::SpanId; /// This struct represents a patch to MIR, which can add /// new statements and basic blocks and patch over block @@ -80,14 +80,14 @@ impl<'tcx> MirPatch<'tcx> { Location { block: bb, statement_index: offset } } - pub fn new_temp(&mut self, ty: Ty<'tcx>, span: Span) -> Local { + pub fn new_temp(&mut self, ty: Ty<'tcx>, span: SpanId) -> Local { let index = self.next_local; self.next_local += 1; self.new_locals.push(LocalDecl::new(ty, span)); Local::new(index as usize) } - pub fn new_internal(&mut self, ty: Ty<'tcx>, span: Span) -> Local { + pub fn new_internal(&mut self, ty: Ty<'tcx>, span: SpanId) -> Local { let index = self.next_local; self.next_local += 1; self.new_locals.push(LocalDecl::new(ty, span).internal()); diff --git a/src/librustc_mir/util/pretty.rs b/src/librustc_mir/util/pretty.rs index ff386cb218304..9cee791036939 100644 --- a/src/librustc_mir/util/pretty.rs +++ b/src/librustc_mir/util/pretty.rs @@ -421,7 +421,11 @@ impl Visitor<'tcx> for ExtraComments<'tcx> { } fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String { - format!("scope {} at {}", scope.index(), tcx.sess.source_map().span_to_string(span)) + format!( + "scope {} at {}", + scope.index(), + tcx.sess.source_map().span_to_string(tcx.reify_span(span)) + ) } /// Prints local variables in a scope tree. diff --git a/src/librustc_mir_build/build/block.rs b/src/librustc_mir_build/build/block.rs index fa783ddcf409a..6f67c0108ed20 100644 --- a/src/librustc_mir_build/build/block.rs +++ b/src/librustc_mir_build/build/block.rs @@ -4,7 +4,7 @@ use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; use crate::hair::*; use rustc_hir as hir; use rustc_middle::mir::*; -use rustc_span::Span; +use rustc_span::SpanId; impl<'a, 'tcx> Builder<'a, 'tcx> { crate fn ast_block( @@ -47,7 +47,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { &mut self, destination: Place<'tcx>, mut block: BasicBlock, - span: Span, + span: SpanId, stmts: Vec>, expr: Option>, safety_mode: BlockSafety, @@ -106,7 +106,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // Declare the bindings, which may create a source scope. let remainder_span = - remainder_scope.span(this.hir.tcx(), &this.hir.region_scope_tree); + remainder_scope.span(this.hir.tcx(), &this.hir.region_scope_tree).into(); let visibility_scope = Some(this.new_source_scope(remainder_span, LintLevel::Inherited, None)); @@ -176,7 +176,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let tail_result_is_ignored = destination_ty.is_unit() || this.block_context.currently_ignores_tail_results(); let span = match expr { - ExprRef::Hair(expr) => expr.span, + ExprRef::Hair(expr) => expr.span.into(), ExprRef::Mirror(ref expr) => expr.span, }; this.block_context.push(BlockFrame::TailExpr { tail_result_is_ignored, span }); @@ -209,7 +209,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } /// If we are changing the safety mode, create a new source scope - fn update_source_scope_for_safety_mode(&mut self, span: Span, safety_mode: BlockSafety) { + fn update_source_scope_for_safety_mode(&mut self, span: SpanId, safety_mode: BlockSafety) { debug!("update_source_scope_for({:?}, {:?})", span, safety_mode); let new_unsafety = match safety_mode { BlockSafety::Safe => None, diff --git a/src/librustc_mir_build/build/expr/as_constant.rs b/src/librustc_mir_build/build/expr/as_constant.rs index 03ec0b48f8bfe..0e0681a50f53b 100644 --- a/src/librustc_mir_build/build/expr/as_constant.rs +++ b/src/librustc_mir_build/build/expr/as_constant.rs @@ -24,7 +24,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ExprKind::Literal { literal, user_ty } => { let user_ty = user_ty.map(|user_ty| { this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation { - span, + span: this.hir.tcx().reify_span(span), user_ty, inferred_ty: ty, }) diff --git a/src/librustc_mir_build/build/expr/as_operand.rs b/src/librustc_mir_build/build/expr/as_operand.rs index 9a75f3afe8f08..67d780be5469f 100644 --- a/src/librustc_mir_build/build/expr/as_operand.rs +++ b/src/librustc_mir_build/build/expr/as_operand.rs @@ -172,7 +172,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { if !ty.is_sized(tcx.at(span), param_env) { // !sized means !copy, so this is an unsized move - assert!(!ty.is_copy_modulo_regions(tcx, param_env, span)); + assert!(!ty.is_copy_modulo_regions(tcx, param_env, span.into())); // As described above, detect the case where we are passing a value of unsized // type, and that value is coming from the deref of a box. diff --git a/src/librustc_mir_build/build/expr/as_place.rs b/src/librustc_mir_build/build/expr/as_place.rs index e08eedc6b6e91..a8fb95501a93e 100644 --- a/src/librustc_mir_build/build/expr/as_place.rs +++ b/src/librustc_mir_build/build/expr/as_place.rs @@ -8,7 +8,7 @@ use rustc_middle::middle::region; use rustc_middle::mir::AssertKind::BoundsCheck; use rustc_middle::mir::*; use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt, Variance}; -use rustc_span::Span; +use rustc_span::SpanId; use rustc_index::vec::Idx; @@ -180,7 +180,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { if let Some(user_ty) = user_ty { let annotation_index = this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation { - span: source_info.span, + span: this.hir.tcx().reify_span(source_info.span), user_ty, inferred_ty: expr.ty, }); @@ -209,7 +209,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { if let Some(user_ty) = user_ty { let annotation_index = this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation { - span: source_info.span, + span: this.hir.tcx().reify_span(source_info.span), user_ty, inferred_ty: expr.ty, }); @@ -286,7 +286,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { mutability: Mutability, fake_borrow_temps: Option<&mut Vec>, temp_lifetime: Option, - expr_span: Span, + expr_span: SpanId, source_info: SourceInfo, ) -> BlockAnd> { let lhs = self.hir.mirror(base); @@ -331,7 +331,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { block: BasicBlock, slice: Place<'tcx>, index: Local, - expr_span: Span, + expr_span: SpanId, source_info: SourceInfo, ) -> BasicBlock { let usize_ty = self.hir.usize_ty(); @@ -359,7 +359,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { base_place: &PlaceBuilder<'tcx>, block: BasicBlock, fake_borrow_temps: &mut Vec, - expr_span: Span, + expr_span: SpanId, source_info: SourceInfo, ) { let tcx = self.hir.tcx(); diff --git a/src/librustc_mir_build/build/expr/as_rvalue.rs b/src/librustc_mir_build/build/expr/as_rvalue.rs index d934ba1dc841e..89eac534335c3 100644 --- a/src/librustc_mir_build/build/expr/as_rvalue.rs +++ b/src/librustc_mir_build/build/expr/as_rvalue.rs @@ -9,7 +9,7 @@ use rustc_middle::middle::region; use rustc_middle::mir::AssertKind; use rustc_middle::mir::*; use rustc_middle::ty::{self, Ty, UpvarSubsts}; -use rustc_span::Span; +use rustc_span::SpanId; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Returns an rvalue suitable for use until the end of the current @@ -271,7 +271,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { &mut self, mut block: BasicBlock, op: BinOp, - span: Span, + span: SpanId, ty: Ty<'tcx>, lhs: Operand<'tcx>, rhs: Operand<'tcx>, @@ -368,7 +368,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { fn limit_capture_mutability( &mut self, - upvar_span: Span, + upvar_span: SpanId, upvar_ty: Ty<'tcx>, temp_lifetime: Option, mut block: BasicBlock, @@ -444,7 +444,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } // Helper to get a `-1` value of the appropriate type - fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> { + fn neg_1_literal(&mut self, span: SpanId, ty: Ty<'tcx>) -> Operand<'tcx> { let param_ty = ty::ParamEnv::empty().and(ty); let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits(); let n = (!0u128) >> (128 - bits); @@ -454,7 +454,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } // Helper to get the minimum value of the appropriate type - fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> { + fn minval_literal(&mut self, span: SpanId, ty: Ty<'tcx>) -> Operand<'tcx> { assert!(ty.is_signed()); let param_ty = ty::ParamEnv::empty().and(ty); let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits(); diff --git a/src/librustc_mir_build/build/expr/into.rs b/src/librustc_mir_build/build/expr/into.rs index 8734d39a6d07b..8a90aba0d8fd8 100644 --- a/src/librustc_mir_build/build/expr/into.rs +++ b/src/librustc_mir_build/build/expr/into.rs @@ -289,7 +289,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let inferred_ty = expr.ty; let user_ty = user_ty.map(|ty| { this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation { - span: source_info.span, + span: this.hir.tcx().reify_span(source_info.span), user_ty: ty, inferred_ty, }) diff --git a/src/librustc_mir_build/build/expr/stmt.rs b/src/librustc_mir_build/build/expr/stmt.rs index 49d6ce39ddfa4..be8a08992886b 100644 --- a/src/librustc_mir_build/build/expr/stmt.rs +++ b/src/librustc_mir_build/build/expr/stmt.rs @@ -151,7 +151,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } this.block_context - .push(BlockFrame::TailExpr { tail_result_is_ignored: true, span: expr.span }); + .push(BlockFrame::TailExpr { tail_result_is_ignored: true, span: expr.span.into() }); return Some(expr.span); } } @@ -162,7 +162,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { unpack!(block = this.as_temp(block, statement_scope, expr, Mutability::Not)); if let Some(span) = adjusted_span { - this.local_decls[temp].source_info.span = span; + this.local_decls[temp].source_info.span = span.into(); this.block_context.pop(); } diff --git a/src/librustc_mir_build/build/matches/mod.rs b/src/librustc_mir_build/build/matches/mod.rs index 1071a4c97df65..506da75e0931a 100644 --- a/src/librustc_mir_build/build/matches/mod.rs +++ b/src/librustc_mir_build/build/matches/mod.rs @@ -16,7 +16,7 @@ use rustc_index::bit_set::BitSet; use rustc_middle::middle::region; use rustc_middle::mir::*; use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty}; -use rustc_span::Span; +use rustc_span::SpanId; use rustc_span::symbol::Symbol; use rustc_target::abi::VariantIdx; use smallvec::{smallvec, SmallVec}; @@ -84,7 +84,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { crate fn match_expr( &mut self, destination: Place<'tcx>, - span: Span, + span: SpanId, mut block: BasicBlock, scrutinee: ExprRef<'tcx>, arms: Vec>, @@ -117,7 +117,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { &mut self, mut block: BasicBlock, scrutinee: ExprRef<'tcx>, - scrutinee_span: Span, + scrutinee_span: SpanId, ) -> BlockAnd> { let scrutinee_place = unpack!(block = self.as_place(block, scrutinee)); // Matching on a `scrutinee_place` with an uninhabited type doesn't @@ -168,7 +168,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { fn lower_match_tree<'pat>( &mut self, block: BasicBlock, - scrutinee_span: Span, + scrutinee_span: SpanId, match_has_guard: bool, candidates: &mut [&mut Candidate<'pat, 'tcx>], ) -> Vec<(Place<'tcx>, Local)> { @@ -220,7 +220,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { &mut self, destination: Place<'tcx>, scrutinee_place: Place<'tcx>, - scrutinee_span: Span, + scrutinee_span: SpanId, arm_candidates: Vec<(&'_ Arm<'tcx>, Candidate<'_, 'tcx>)>, outer_source_info: SourceInfo, fake_borrow_temps: Vec<(Place<'tcx>, Local)>, @@ -284,7 +284,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { candidate: Candidate<'_, 'tcx>, guard: Option<&Guard<'tcx>>, fake_borrow_temps: &Vec<(Place<'tcx>, Local)>, - scrutinee_span: Span, + scrutinee_span: SpanId, arm_scope: Option, ) -> BasicBlock { if candidate.subcandidates.is_empty() { @@ -406,6 +406,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let ty_source_info = self.source_info(user_ty_span); let user_ty = pat_ascription_ty.user_ty( + self.hir.tcx(), &mut self.canonical_user_type_annotations, place.ty(&self.local_decls, self.hir.tcx()).ty, ty_source_info.span, @@ -503,10 +504,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { crate fn declare_bindings( &mut self, mut visibility_scope: Option, - scope_span: Span, + scope_span: SpanId, pattern: &Pat<'tcx>, has_guard: ArmHasGuard, - opt_match_place: Option<(Option<&Place<'tcx>>, Span)>, + opt_match_place: Option<(Option<&Place<'tcx>>, SpanId)>, ) -> Option { debug!("declare_bindings: pattern={:?}", pattern); self.visit_primary_bindings( @@ -541,7 +542,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { &mut self, block: BasicBlock, var: HirId, - span: Span, + span: SpanId, for_guard: ForGuard, schedule_drop: bool, ) -> Place<'tcx> { @@ -555,7 +556,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { Place::from(local_id) } - crate fn schedule_drop_for_binding(&mut self, var: HirId, span: Span, for_guard: ForGuard) { + crate fn schedule_drop_for_binding(&mut self, var: HirId, span: SpanId, for_guard: ForGuard) { let local_id = self.var_local_id(var, for_guard); let region_scope = self.hir.region_scope_tree.var_scope(var.local_id); self.schedule_drop(span, region_scope, local_id, DropKind::Value); @@ -574,7 +575,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { Symbol, BindingMode, HirId, - Span, + SpanId, Ty<'tcx>, UserTypeProjections, ), @@ -640,7 +641,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // Note that the variance doesn't apply here, as we are tracking the effect // of `user_ty` on any bindings contained with subpattern. let annotation = CanonicalUserTypeAnnotation { - span: user_ty_span, + span: self.hir.tcx().reify_span(user_ty_span), user_ty: user_ty.user_ty, inferred_ty: subpattern.ty, }; @@ -682,8 +683,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { #[derive(Debug)] struct Candidate<'pat, 'tcx> { - /// `Span` of the original pattern that gave rise to this candidate - span: Span, + /// `SpanId` of the original pattern that gave rise to this candidate + span: SpanId, /// This `Candidate` has a guard. has_guard: bool, @@ -760,7 +761,7 @@ fn traverse_candidate<'pat, 'tcx: 'pat, C, T, I>( #[derive(Clone, Debug)] struct Binding<'tcx> { - span: Span, + span: SpanId, source: Place<'tcx>, name: Symbol, var_id: HirId, @@ -774,7 +775,7 @@ struct Binding<'tcx> { /// influence region inference. #[derive(Clone, Debug)] struct Ascription<'tcx> { - span: Span, + span: SpanId, source: Place<'tcx>, user_ty: PatTyProj<'tcx>, variance: ty::Variance, @@ -836,7 +837,7 @@ enum TestKind<'tcx> { #[derive(Debug)] crate struct Test<'tcx> { - span: Span, + span: SpanId, kind: TestKind<'tcx>, } @@ -888,7 +889,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// `otherwise_block`. fn match_candidates<'pat>( &mut self, - span: Span, + span: SpanId, start_block: BasicBlock, otherwise_block: &mut Option, candidates: &mut [&mut Candidate<'pat, 'tcx>], @@ -935,7 +936,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { fn match_simplified_candidates( &mut self, - span: Span, + span: SpanId, start_block: BasicBlock, otherwise_block: &mut Option, candidates: &mut [&mut Candidate<'_, 'tcx>], @@ -1143,7 +1144,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// ``` fn test_candidates_with_or( &mut self, - span: Span, + span: SpanId, candidates: &mut [&mut Candidate<'_, 'tcx>], block: BasicBlock, otherwise_block: &mut Option, @@ -1201,7 +1202,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { candidate: &mut Candidate<'pat, 'tcx>, otherwise: &mut Option, pats: &'pat [Pat<'tcx>], - or_span: Span, + or_span: SpanId, place: Place<'tcx>, fake_borrows: &mut Option>>, ) { @@ -1373,7 +1374,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// once. fn test_candidates<'pat, 'b, 'c>( &mut self, - span: Span, + span: SpanId, mut candidates: &'b mut [&'c mut Candidate<'pat, 'tcx>], block: BasicBlock, otherwise_block: &mut Option, @@ -1523,7 +1524,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { fn calculate_fake_borrows<'b>( &mut self, fake_borrows: &'b FxHashSet>, - temp_span: Span, + temp_span: SpanId, ) -> Vec<(Place<'tcx>, Local)> { let tcx = self.hir.tcx(); @@ -1590,7 +1591,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { parent_bindings: &[(Vec>, Vec>)], guard: Option<&Guard<'tcx>>, fake_borrows: &Vec<(Place<'tcx>, Local)>, - scrutinee_span: Span, + scrutinee_span: SpanId, schedule_drops: bool, ) -> BasicBlock { debug!("bind_and_guard_matched_candidate(candidate={:?})", candidate); @@ -1727,7 +1728,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { Guard::If(e) => self.hir.mirror(e.clone()), }; let source_info = self.source_info(guard.span); - let guard_end = self.source_info(tcx.sess.source_map().end_point(guard.span)); + let guard_end = self.source_info(tcx.sess.source_map().end_point(tcx.reify_span(guard.span)).into()); let (post_guard_block, otherwise_post_guard_block) = self.test_bool(block, guard, source_info); let guard_frame = self.guard_context.pop().unwrap(); @@ -1831,6 +1832,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); let user_ty = ascription.user_ty.clone().user_ty( + self.hir.tcx(), &mut self.canonical_user_type_annotations, ascription.source.ty(&self.local_decls, self.hir.tcx()).ty, source_info.span, @@ -1950,8 +1952,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { var_ty: Ty<'tcx>, user_ty: UserTypeProjections, has_guard: ArmHasGuard, - opt_match_place: Option<(Option>, Span)>, - pat_span: Span, + opt_match_place: Option<(Option>, SpanId)>, + pat_span: SpanId, ) { debug!( "declare_binding(var_id={:?}, name={:?}, mode={:?}, var_ty={:?}, \ diff --git a/src/librustc_mir_build/build/misc.rs b/src/librustc_mir_build/build/misc.rs index e8933ff8aa749..7bf91dfd9bb78 100644 --- a/src/librustc_mir_build/build/misc.rs +++ b/src/librustc_mir_build/build/misc.rs @@ -6,7 +6,7 @@ use crate::build::Builder; use rustc_middle::ty::{self, Ty}; use rustc_middle::mir::*; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{SpanId, DUMMY_SPID}; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Adds a new temporary value of type `ty` storing the result of @@ -14,7 +14,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// /// N.B., **No cleanup is scheduled for this temporary.** You should /// call `schedule_drop` once the temporary is initialized. - crate fn temp(&mut self, ty: Ty<'tcx>, span: Span) -> Place<'tcx> { + crate fn temp(&mut self, ty: Ty<'tcx>, span: SpanId) -> Place<'tcx> { let temp = self.local_decls.push(LocalDecl::new(ty, span)); let place = Place::from(temp); debug!("temp: created temp {:?} with type {:?}", place, self.local_decls[temp].ty); @@ -25,7 +25,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// without any user type annotation. crate fn literal_operand( &mut self, - span: Span, + span: SpanId, literal: &'tcx ty::Const<'tcx>, ) -> Operand<'tcx> { let constant = box Constant { span, user_ty: None, literal }; @@ -34,7 +34,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // Returns a zero literal operand for the appropriate type, works for // bool, char and integers. - crate fn zero_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> { + crate fn zero_literal(&mut self, span: SpanId, ty: Ty<'tcx>) -> Operand<'tcx> { let literal = ty::Const::from_bits(self.hir.tcx(), 0, ty::ParamEnv::empty().and(ty)); self.literal_operand(span, literal) @@ -64,7 +64,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { crate fn consume_by_copy_or_move(&self, place: Place<'tcx>) -> Operand<'tcx> { let tcx = self.hir.tcx(); let ty = place.ty(&self.local_decls, tcx).ty; - if !self.hir.type_is_copy_modulo_regions(ty, DUMMY_SP) { + if !self.hir.type_is_copy_modulo_regions(ty, DUMMY_SPID) { Operand::Move(place) } else { Operand::Copy(place) diff --git a/src/librustc_mir_build/build/mod.rs b/src/librustc_mir_build/build/mod.rs index b30b57ea9217a..2a66cd7ff11cb 100644 --- a/src/librustc_mir_build/build/mod.rs +++ b/src/librustc_mir_build/build/mod.rs @@ -15,7 +15,7 @@ use rustc_middle::mir::*; use rustc_middle::ty::subst::Subst; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; use rustc_span::symbol::kw; -use rustc_span::Span; +use rustc_span::SpanId; use rustc_target::spec::abi::Abi; use rustc_target::spec::PanicStrategy; @@ -107,7 +107,7 @@ fn mir_build(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Body<'_> { let opt_ty_info; let self_arg; if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) { - opt_ty_info = fn_decl.inputs.get(index).map(|ty| ty.span); + opt_ty_info = fn_decl.inputs.get(index).map(|ty| ty.span.into()); self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() { match fn_decl.implicit_self { hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm), @@ -158,7 +158,7 @@ fn mir_build(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Body<'_> { safety, abi, return_ty, - return_ty_span, + return_ty_span.into(), body, ); mir.yield_ty = yield_ty; @@ -178,7 +178,7 @@ fn mir_build(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Body<'_> { let return_ty = cx.tables().node_type(id); - build::construct_const(cx, body_id, return_ty, return_ty_span) + build::construct_const(cx, body_id, return_ty, return_ty_span.into()) }; lints::check(tcx, &body, def_id); @@ -243,8 +243,8 @@ enum BlockFrame { /// Example: `let _ = { STMT_1; EXPR };` tail_result_is_ignored: bool, - /// `Span` of the tail expression. - span: Span, + /// `SpanId` of the tail expression. + span: SpanId, }, /// Generic mark meaning that the block occurred as a subexpression @@ -278,7 +278,7 @@ struct Builder<'a, 'tcx> { hir: Cx<'a, 'tcx>, cfg: CFG<'tcx>, - fn_span: Span, + fn_span: SpanId, arg_count: usize, generator_kind: Option, @@ -545,7 +545,7 @@ fn should_abort_on_panic(tcx: TyCtxt<'_>, fn_def_id: LocalDefId, _abi: Abi) -> b struct ArgInfo<'tcx>( Ty<'tcx>, - Option, + Option, Option<&'tcx hir::Param<'tcx>>, Option, ); @@ -557,7 +557,7 @@ fn construct_fn<'a, 'tcx, A>( safety: Safety, abi: Abi, return_ty: Ty<'tcx>, - return_ty_span: Span, + return_ty_span: SpanId, body: &'tcx hir::Body<'tcx>, ) -> Body<'tcx> where @@ -573,7 +573,7 @@ where let mut builder = Builder::new( hir, - span, + span.into(), arguments.len(), safety, return_ty, @@ -585,12 +585,12 @@ where region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite }; let arg_scope = region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::Arguments }; - let source_info = builder.source_info(span); + let source_info = builder.source_info(span.into()); let call_site_s = (call_site_scope, source_info); unpack!(builder.in_scope(call_site_s, LintLevel::Inherited, |builder| { let arg_scope_s = (arg_scope, source_info); // Attribute epilogue to function's closing brace - let fn_end = span.shrink_to_hi(); + let fn_end = span.shrink_to_hi().into(); let return_block = unpack!(builder.in_breakable_scope(None, Place::return_place(), fn_end, |builder| { Some(builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| { @@ -631,11 +631,11 @@ fn construct_const<'a, 'tcx>( hir: Cx<'a, 'tcx>, body_id: hir::BodyId, const_ty: Ty<'tcx>, - const_ty_span: Span, + const_ty_span: SpanId, ) -> Body<'tcx> { let tcx = hir.tcx(); let owner_id = tcx.hir().body_owner(body_id); - let span = tcx.hir().span(owner_id); + let span = tcx.hir().span(owner_id).into(); let mut builder = Builder::new(hir, span, 0, Safety::Safe, const_ty, const_ty_span, None); let mut block = START_BLOCK; @@ -664,7 +664,7 @@ fn construct_const<'a, 'tcx>( fn construct_error<'a, 'tcx>(hir: Cx<'a, 'tcx>, body_id: hir::BodyId) -> Body<'tcx> { let tcx = hir.tcx(); let owner_id = tcx.hir().body_owner(body_id); - let span = tcx.hir().span(owner_id); + let span = tcx.hir().span(owner_id).into(); let ty = tcx.types.err; let num_params = match hir.body_owner_kind { hir::BodyOwnerKind::Fn => tcx.hir().fn_decl_by_hir_id(owner_id).unwrap().inputs.len(), @@ -699,11 +699,11 @@ fn construct_error<'a, 'tcx>(hir: Cx<'a, 'tcx>, body_id: hir::BodyId) -> Body<'t impl<'a, 'tcx> Builder<'a, 'tcx> { fn new( hir: Cx<'a, 'tcx>, - span: Span, + span: SpanId, arg_count: usize, safety: Safety, return_ty: Ty<'tcx>, - return_span: Span, + return_span: SpanId, generator_kind: Option, ) -> Builder<'a, 'tcx> { let lint_level = LintLevel::Explicit(hir.root_lint_level); @@ -770,7 +770,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // Allocate locals for the function arguments for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() { let source_info = - SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span)); + SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span.into())); 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. @@ -840,7 +840,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { self.var_debug_info.push(VarDebugInfo { name, - source_info: SourceInfo::outermost(tcx_hir.span(var_id)), + source_info: SourceInfo::outermost(tcx_hir.span(var_id).into()), place: Place { local: closure_env_arg, projection: tcx.intern_place_elems(&projs), @@ -862,7 +862,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| arg.pat.span).into(), argument_scope, local, DropKind::Value, @@ -902,7 +902,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { _ => { scope = self.declare_bindings( scope, - ast_body.span, + ast_body.span.into(), &pattern, matches::ArmHasGuard(false), Some((Some(&place), span)), @@ -927,7 +927,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { &mut self, arg_hir_id: hir::HirId, original_source_scope: SourceScope, - pattern_span: Span, + pattern_span: SpanId, ) { let tcx = self.hir.tcx(); let current_root = tcx.maybe_lint_level_root_bounded(arg_hir_id, self.hir.root_lint_level); diff --git a/src/librustc_mir_build/build/scope.rs b/src/librustc_mir_build/build/scope.rs index 710a41bc8fdb5..71230be50ace4 100644 --- a/src/librustc_mir_build/build/scope.rs +++ b/src/librustc_mir_build/build/scope.rs @@ -88,7 +88,7 @@ use rustc_hir as hir; use rustc_index::vec::IndexVec; use rustc_middle::middle::region; use rustc_middle::mir::*; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{SpanId, DUMMY_SPID}; #[derive(Debug)] pub struct Scopes<'tcx> { @@ -113,7 +113,7 @@ struct Scope { region_scope: region::Scope, /// the span of that region_scope - region_scope_span: Span, + region_scope_span: SpanId, /// set of places to drop when exiting this scope. This starts /// out empty but grows as variables are declared during the @@ -240,7 +240,7 @@ impl DropTree { // The root node of the tree doesn't represent a drop, but instead // represents the block in the tree that should be jumped to once all // of the required drops have been performed. - let fake_source_info = SourceInfo::outermost(DUMMY_SP); + let fake_source_info = SourceInfo::outermost(DUMMY_SPID); let fake_data = DropData { source_info: fake_source_info, local: Local::MAX, kind: DropKind::Storage }; let drop_idx = DropIdx::MAX; @@ -380,8 +380,8 @@ impl DropTree { // Diagnostics don't use this `Span` but debuginfo // might. Since we don't want breakpoints to be placed // here, especially when this is on an unwind path, we - // use `DUMMY_SP`. - let source_info = SourceInfo { span: DUMMY_SP, ..drop_data.0.source_info }; + // use `DUMMY_SPID`. + let source_info = SourceInfo { span: DUMMY_SPID, ..drop_data.0.source_info }; let terminator = TerminatorKind::Goto { target }; cfg.terminate(block, source_info, terminator); } @@ -420,7 +420,7 @@ impl<'tcx> Scopes<'tcx> { scope } - fn scope_index(&self, region_scope: region::Scope, span: Span) -> usize { + fn scope_index(&self, region_scope: region::Scope, span: SpanId) -> usize { self.scopes .iter() .rposition(|scope| scope.region_scope == region_scope) @@ -443,7 +443,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { &mut self, loop_block: Option, break_destination: Place<'tcx>, - span: Span, + span: SpanId, f: F, ) -> BlockAnd<()> where @@ -679,7 +679,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// Creates a new source scope, nested in the current one. crate fn new_source_scope( &mut self, - span: Span, + span: SpanId, lint_level: LintLevel, safety: Option, ) -> SourceScope { @@ -710,7 +710,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } /// Given a span and the current source scope, make a SourceInfo. - crate fn source_info(&self, span: Span) -> SourceInfo { + crate fn source_info(&self, span: SpanId) -> SourceInfo { SourceInfo { span, scope: self.source_scope } } @@ -753,7 +753,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // ================ crate fn schedule_drop_storage_and_value( &mut self, - span: Span, + span: SpanId, region_scope: region::Scope, local: Local, ) { @@ -767,7 +767,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// place, or a function parameter. crate fn schedule_drop( &mut self, - span: Span, + span: SpanId, region_scope: region::Scope, local: Local, drop_kind: DropKind, @@ -848,7 +848,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let region_scope_span = region_scope.span(self.hir.tcx(), &self.hir.region_scope_tree); // Attribute scope exit drops to scope's closing brace. - let scope_end = self.hir.tcx().sess.source_map().end_point(region_scope_span); + let scope_end = self.hir.tcx().sess.source_map().end_point(region_scope_span).into(); scope.drops.push(DropData { source_info: SourceInfo { span: scope_end, scope: scope.source_scope }, @@ -1077,7 +1077,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { crate fn build_drop_and_replace( &mut self, block: BasicBlock, - span: Span, + span: SpanId, location: Place<'tcx>, value: Operand<'tcx>, ) -> BlockAnd<()> { @@ -1103,7 +1103,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { cond: Operand<'tcx>, expected: bool, msg: AssertMessage<'tcx>, - span: Span, + span: SpanId, ) -> BasicBlock { let source_info = self.source_info(span); let success_block = self.cfg.start_new_block(); @@ -1311,7 +1311,7 @@ impl<'a, 'tcx: 'a> Builder<'a, 'tcx> { fn build_unwind_tree( cfg: &mut CFG<'tcx>, drops: &mut DropTree, - fn_span: Span, + fn_span: SpanId, should_abort: bool, resume_block: &mut Option, ) { diff --git a/src/librustc_mir_build/hair/cx/block.rs b/src/librustc_mir_build/hair/cx/block.rs index c7b53024666d9..d1fab8908d869 100644 --- a/src/librustc_mir_build/hair/cx/block.rs +++ b/src/librustc_mir_build/hair/cx/block.rs @@ -21,7 +21,7 @@ impl<'tcx> Mirror<'tcx> for &'tcx hir::Block<'tcx> { 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: self.span.into(), stmts, expr: self.expr.to_ref(), safety_mode: match self.rules { @@ -73,7 +73,7 @@ fn mirror_stmts<'a, 'tcx>( kind: Box::new(PatKind::AscribeUserType { ascription: hair::pattern::Ascription { user_ty: PatTyProj::from_user_type(user_ty), - user_ty_span: ty.span, + user_ty_span: ty.span.into(), variance: ty::Variance::Covariant, }, subpattern: pattern, @@ -110,7 +110,7 @@ crate fn to_expr_ref<'a, 'tcx>( let expr = Expr { ty: block_ty, temp_lifetime, - span: block.span, + span: block.span.into(), 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 8d572465d62c1..ac0d19011a4a0 100644 --- a/src/librustc_mir_build/hair/cx/expr.rs +++ b/src/librustc_mir_build/hair/cx/expr.rs @@ -13,7 +13,7 @@ use rustc_middle::ty::adjustment::{ }; use rustc_middle::ty::subst::{InternalSubsts, SubstsRef}; use rustc_middle::ty::{self, AdtKind, Ty}; -use rustc_span::Span; +use rustc_span::SpanId; impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr<'tcx> { type Output = Expr<'tcx>; @@ -36,7 +36,7 @@ impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr<'tcx> { expr = Expr { temp_lifetime, ty: expr.ty, - span: self.span, + span: self.span.into(), kind: ExprKind::Scope { region_scope: expr_scope, value: expr.to_ref(), @@ -50,7 +50,7 @@ impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr<'tcx> { expr = Expr { temp_lifetime, ty: expr.ty, - span: self.span, + span: self.span.into(), kind: ExprKind::Scope { region_scope, value: expr.to_ref(), @@ -85,7 +85,7 @@ fn apply_adjustment<'a, 'tcx>( let mut adjust_span = |expr: &mut Expr<'tcx>| { if let ExprKind::Block { body } = expr.kind { if let Some(ref last_expr) = body.expr { - span = last_expr.span; + span = last_expr.span.into(); expr.span = span; } } @@ -141,7 +141,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( // Here comes the interesting stuff: hir::ExprKind::MethodCall(_, method_span, ref args) => { // Rewrite a.b(c) into UFCS form like Trait::b(a, c) - let expr = method_callee(cx, expr, method_span, None); + let expr = method_callee(cx, expr, method_span.into(), None); let args = args.iter().map(|e| e.to_ref()).collect(); ExprKind::Call { ty: expr.ty, fun: expr.to_ref(), args, from_hir_call: true } } @@ -155,13 +155,13 @@ fn make_mirror_unadjusted<'a, 'tcx>( // rewrite f(u, v) into FnOnce::call_once(f, (u, v)) - let method = method_callee(cx, expr, fun.span, None); + let method = method_callee(cx, expr, fun.span.into(), None); let arg_tys = args.iter().map(|e| cx.tables().expr_ty_adjusted(e)); let tupled_args = Expr { ty: cx.tcx.mk_tup(arg_tys), temp_lifetime, - span: expr.span, + span: expr.span.into(), kind: ExprKind::Tuple { fields: args.iter().map(ToRef::to_ref).collect() }, }; @@ -243,7 +243,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( } hir::ExprKind::Lit(ref lit) => ExprKind::Literal { - literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, false), + literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span.into(), false), user_ty: None, }, @@ -257,13 +257,13 @@ fn make_mirror_unadjusted<'a, 'tcx>( (hir::BinOpKind::And, hir::Constness::Const) if !cx.tcx.features().const_if_match => { - cx.control_flow_destroyed.push((op.span, "`&&` operator".into())); + cx.control_flow_destroyed.push((op.span.into(), "`&&` operator".into())); ExprKind::Binary { op: BinOp::BitAnd, lhs: lhs.to_ref(), rhs: rhs.to_ref() } } (hir::BinOpKind::Or, hir::Constness::Const) if !cx.tcx.features().const_if_match => { - cx.control_flow_destroyed.push((op.span, "`||` operator".into())); + cx.control_flow_destroyed.push((op.span.into(), "`||` operator".into())); ExprKind::Binary { op: BinOp::BitOr, lhs: lhs.to_ref(), rhs: rhs.to_ref() } } @@ -316,7 +316,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( } else { if let hir::ExprKind::Lit(ref lit) = arg.kind { ExprKind::Literal { - literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true), + literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span.into(), true), user_ty: None, } } else { @@ -497,7 +497,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( Expr { temp_lifetime, ty: var_ty, - span: expr.span, + span: expr.span.into(), kind: ExprKind::Literal { literal, user_ty: None }, } .to_ref() @@ -517,7 +517,8 @@ fn make_mirror_unadjusted<'a, 'tcx>( ty: var_ty, })); let bin = ExprKind::Binary { op: BinOp::Add, lhs, rhs: offset }; - Expr { temp_lifetime, ty: var_ty, span: expr.span, kind: bin }.to_ref() + Expr { temp_lifetime, ty: var_ty, span: expr.span.into(), kind: bin } + .to_ref() } None => offset, } @@ -531,7 +532,8 @@ fn make_mirror_unadjusted<'a, 'tcx>( if let Some(user_ty) = user_ty { // NOTE: Creating a new Expr and wrapping a Cast inside of it may be // inefficient, revisit this when performance becomes an issue. - let cast_expr = Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind: cast }; + let cast_expr = + Expr { temp_lifetime, ty: expr_ty, span: expr.span.into(), kind: cast }; debug!("make_mirror_unadjusted: (cast) user_ty={:?}", user_ty); ExprKind::ValueTypeAscription { @@ -561,7 +563,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( hir::ExprKind::Err => unreachable!(), }; - Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind } + Expr { temp_lifetime, ty: expr_ty, span: expr.span.into(), kind } } fn user_substs_applied_to_res<'tcx>( @@ -602,7 +604,7 @@ fn user_substs_applied_to_res<'tcx>( fn method_callee<'a, 'tcx>( cx: &mut Cx<'a, 'tcx>, expr: &hir::Expr<'_>, - span: Span, + span: SpanId, overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>, ) -> Expr<'tcx> { let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id); @@ -665,7 +667,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: arm.span.into(), } } @@ -746,7 +748,7 @@ fn convert_path_expr<'a, 'tcx>( arg: Expr { ty, temp_lifetime, - span: expr.span, + span: expr.span.into(), kind: ExprKind::StaticRef { literal: ty::Const::from_scalar(cx.tcx, Scalar::Ptr(ptr.into()), ty), def_id: id, @@ -815,12 +817,12 @@ fn convert_var<'tcx>( Expr { ty: closure_ty, temp_lifetime, - span: expr.span, + span: expr.span.into(), kind: ExprKind::Deref { arg: Expr { ty: ref_closure_ty, temp_lifetime, - span: expr.span, + span: expr.span.into(), kind: ExprKind::SelfRef, } .to_ref(), @@ -835,12 +837,12 @@ fn convert_var<'tcx>( Expr { ty: closure_ty, temp_lifetime, - span: expr.span, + span: expr.span.into(), kind: ExprKind::Deref { arg: Expr { ty: ref_closure_ty, temp_lifetime, - span: expr.span, + span: expr.span.into(), kind: ExprKind::SelfRef, } .to_ref(), @@ -850,12 +852,17 @@ fn convert_var<'tcx>( ty::ClosureKind::FnOnce => Expr { ty: closure_ty, temp_lifetime, - span: expr.span, + span: expr.span.into(), kind: ExprKind::SelfRef, }, } } else { - Expr { ty: closure_ty, temp_lifetime, span: expr.span, kind: ExprKind::SelfRef } + Expr { + ty: closure_ty, + temp_lifetime, + span: expr.span.into(), + kind: ExprKind::SelfRef, + } }; // at this point we have `self.n`, which loads up the upvar @@ -873,7 +880,7 @@ fn convert_var<'tcx>( borrow.region, ty::TypeAndMut { ty: var_ty, mutbl: borrow.kind.to_mutbl_lossy() }, ), - span: expr.span, + span: expr.span.into(), kind: field_kind, } .to_ref(), @@ -910,7 +917,7 @@ fn overloaded_operator<'a, 'tcx>( expr: &'tcx hir::Expr<'tcx>, args: Vec>, ) -> ExprKind<'tcx> { - let fun = method_callee(cx, expr, expr.span, None); + let fun = method_callee(cx, expr, expr.span.into(), None); ExprKind::Call { ty: fun.ty, fun: fun.to_ref(), args, from_hir_call: false } } @@ -942,11 +949,11 @@ fn overloaded_place<'a, 'tcx>( // construct the complete expression `foo()` for the overloaded call, // which will yield the &T type let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id); - let fun = method_callee(cx, expr, expr.span, overloaded_callee); + let fun = method_callee(cx, expr, expr.span.into(), overloaded_callee); let ref_expr = Expr { temp_lifetime, ty: ref_ty, - span: expr.span, + span: expr.span.into(), kind: ExprKind::Call { ty: fun.ty, fun: fun.to_ref(), args, from_hir_call: false }, }; @@ -970,7 +977,7 @@ fn capture_upvar<'tcx>( let captured_var = Expr { temp_lifetime, ty: var_ty, - span: closure_expr.span, + span: closure_expr.span.into(), kind: convert_var(cx, closure_expr, var_hir_id), }; match upvar_capture { @@ -984,7 +991,7 @@ fn capture_upvar<'tcx>( Expr { temp_lifetime, ty: upvar_ty, - span: closure_expr.span, + span: closure_expr.span.into(), kind: ExprKind::Borrow { borrow_kind, arg: captured_var.to_ref() }, } .to_ref() diff --git a/src/librustc_mir_build/hair/cx/mod.rs b/src/librustc_mir_build/hair/cx/mod.rs index 46607fd07cdd7..8446904140144 100644 --- a/src/librustc_mir_build/hair/cx/mod.rs +++ b/src/librustc_mir_build/hair/cx/mod.rs @@ -49,7 +49,7 @@ crate struct Cx<'a, 'tcx> { check_overflow: bool, /// See field with the same name on `mir::Body`. - control_flow_destroyed: Vec<(Span, String)>, + control_flow_destroyed: Vec<(SpanId, String)>, } impl<'a, 'tcx> Cx<'a, 'tcx> { @@ -93,7 +93,7 @@ impl<'a, 'tcx> Cx<'a, 'tcx> { } } - crate fn control_flow_destroyed(self) -> Vec<(Span, String)> { + crate fn control_flow_destroyed(self) -> Vec<(SpanId, String)> { self.control_flow_destroyed } } @@ -132,7 +132,7 @@ impl<'a, 'tcx> Cx<'a, 'tcx> { &mut self, lit: &'tcx ast::LitKind, ty: Ty<'tcx>, - sp: Span, + sp: SpanId, neg: bool, ) -> &'tcx ty::Const<'tcx> { trace!("const_eval_literal: {:#?}, {:?}, {:?}, {:?}", lit, ty, sp, neg); @@ -204,8 +204,8 @@ impl<'a, 'tcx> Cx<'a, 'tcx> { self.check_overflow } - crate fn type_is_copy_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool { - self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) + crate fn type_is_copy_modulo_regions(&self, ty: Ty<'tcx>, span: SpanId) -> bool { + self.infcx.type_is_copy_modulo_regions(self.param_env, ty, self.infcx.tcx.reify_span(span)) } } diff --git a/src/librustc_mir_build/hair/mod.rs b/src/librustc_mir_build/hair/mod.rs index 601e4412512ab..32ca1bab37c02 100644 --- a/src/librustc_mir_build/hair/mod.rs +++ b/src/librustc_mir_build/hair/mod.rs @@ -13,7 +13,7 @@ use rustc_middle::mir::{BinOp, BorrowKind, Field, UnOp}; use rustc_middle::ty::adjustment::PointerCast; use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::{AdtDef, Const, Ty, UpvarSubsts, UserType}; -use rustc_span::Span; +use rustc_span::SpanId; use rustc_target::abi::VariantIdx; crate mod constant; @@ -36,7 +36,7 @@ crate struct Block<'tcx> { crate targeted_by_break: bool, crate region_scope: region::Scope, crate opt_destruction_scope: Option, - crate span: Span, + crate span: SpanId, crate stmts: Vec>, crate expr: Option>, crate safety_mode: BlockSafety, @@ -95,7 +95,7 @@ crate enum StmtKind<'tcx> { // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(target_arch = "x86_64")] -rustc_data_structures::static_assert_size!(Expr<'_>, 168); +rustc_data_structures::static_assert_size!(Expr<'_>, 176); /// The Hair trait implementor lowers their expressions (`&'tcx H::Expr`) /// into instances of this `Expr` enum. This lowering can be done @@ -121,7 +121,7 @@ crate struct Expr<'tcx> { crate temp_lifetime: Option, /// span of the expression in the source - crate span: Span, + crate span: SpanId, /// kind of expression crate kind: ExprKind<'tcx>, @@ -312,7 +312,7 @@ crate struct Arm<'tcx> { crate body: ExprRef<'tcx>, crate lint_level: LintLevel, crate scope: region::Scope, - crate span: Span, + crate span: SpanId, } #[derive(Clone, Debug)] @@ -327,9 +327,9 @@ crate enum LogicalOp { } impl<'tcx> ExprRef<'tcx> { - crate fn span(&self) -> Span { + crate fn span(&self) -> SpanId { match self { - ExprRef::Hair(expr) => expr.span, + ExprRef::Hair(expr) => expr.span.into(), ExprRef::Mirror(expr) => expr.span, } } diff --git a/src/librustc_mir_build/hair/pattern/_match.rs b/src/librustc_mir_build/hair/pattern/_match.rs index f6941d3293b5c..5c64e94e6184a 100644 --- a/src/librustc_mir_build/hair/pattern/_match.rs +++ b/src/librustc_mir_build/hair/pattern/_match.rs @@ -244,7 +244,7 @@ use rustc_middle::mir::Field; use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::{self, Const, Ty, TyCtxt, TypeFoldable, VariantDef}; use rustc_session::lint; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{SpanId, DUMMY_SPID}; use rustc_target::abi::{Integer, Size, VariantIdx}; use arena::TypedArena; @@ -1028,7 +1028,7 @@ impl<'tcx> Constructor<'tcx> { NonExhaustive => PatKind::Wild, }; - Pat { ty, span: DUMMY_SP, kind: Box::new(pat) } + Pat { ty, span: DUMMY_SPID, kind: Box::new(pat) } } /// Like `apply`, but where all the subpatterns are wildcards `_`. @@ -1135,7 +1135,7 @@ crate enum WitnessPreference { #[derive(Copy, Clone, Debug)] struct PatCtxt<'tcx> { ty: Ty<'tcx>, - span: Span, + span: SpanId, } /// A witness of non-exhaustiveness for error reporting, represented @@ -1341,7 +1341,7 @@ fn all_constructors<'a, 'tcx>( struct IntRange<'tcx> { range: RangeInclusive, ty: Ty<'tcx>, - span: Span, + span: SpanId, } impl<'tcx> IntRange<'tcx> { @@ -1385,7 +1385,7 @@ impl<'tcx> IntRange<'tcx> { tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, value: &Const<'tcx>, - span: Span, + span: SpanId, ) -> Option> { if let Some((target_size, bias)) = Self::integral_size_and_signed_bias(tcx, value.ty) { let ty = value.ty; @@ -1416,7 +1416,7 @@ impl<'tcx> IntRange<'tcx> { hi: u128, ty: Ty<'tcx>, end: &RangeEnd, - span: Span, + span: SpanId, ) -> Option> { if Self::is_integral(ty) { // Perform a shift if the underlying types are signed, @@ -1540,7 +1540,7 @@ impl<'tcx> IntRange<'tcx> { }; // This is a brand new pattern, so we don't reuse `self.span`. - Pat { ty: self.ty, span: DUMMY_SP, kind: Box::new(kind) } + Pat { ty: self.ty, span: DUMMY_SPID, kind: Box::new(kind) } } } @@ -1753,22 +1753,30 @@ crate fn is_useful<'p, 'tcx>( if missing_ctors.is_empty() { let (all_ctors, _) = missing_ctors.into_inner(); - split_grouped_constructors(cx.tcx, cx.param_env, pcx, all_ctors, matrix, DUMMY_SP, None) - .into_iter() - .map(|c| { - is_useful_specialized( - cx, - matrix, - v, - c, - pcx.ty, - witness_preference, - hir_id, - is_under_guard, - ) - }) - .find(|result| result.is_useful()) - .unwrap_or(NotUseful) + split_grouped_constructors( + cx.tcx, + cx.param_env, + pcx, + all_ctors, + matrix, + DUMMY_SPID, + None, + ) + .into_iter() + .map(|c| { + is_useful_specialized( + cx, + matrix, + v, + c, + pcx.ty, + witness_preference, + hir_id, + is_under_guard, + ) + }) + .find(|result| result.is_useful()) + .unwrap_or(NotUseful) } else { let matrix = matrix.specialize_wildcard(); let v = v.to_tail(); @@ -1913,7 +1921,7 @@ fn pat_constructor<'tcx>( // second pattern to lint about unreachable match arms. fn slice_pat_covered_by_const<'tcx>( tcx: TyCtxt<'tcx>, - _span: Span, + _span: SpanId, const_val: &'tcx ty::Const<'tcx>, prefix: &[Pat<'tcx>], slice: &Option>, @@ -2020,7 +2028,7 @@ fn split_grouped_constructors<'p, 'tcx>( pcx: PatCtxt<'tcx>, ctors: Vec>, matrix: &Matrix<'p, 'tcx>, - span: Span, + span: SpanId, hir_id: Option, ) -> Vec> { let ty = pcx.ty; @@ -2264,7 +2272,7 @@ fn lint_overlapping_patterns<'tcx>( int_range.span, &format!( "this range overlaps on `{}`", - IntRange { range: int_range.range, ty, span: DUMMY_SP }.to_pat(tcx), + IntRange { range: int_range.range, ty, span: DUMMY_SPID }.to_pat(tcx), ), ); } diff --git a/src/librustc_mir_build/hair/pattern/check_match.rs b/src/librustc_mir_build/hair/pattern/check_match.rs index 65ff311d18215..bab3752e94197 100644 --- a/src/librustc_mir_build/hair/pattern/check_match.rs +++ b/src/librustc_mir_build/hair/pattern/check_match.rs @@ -16,7 +16,7 @@ use rustc_session::lint::builtin::BINDINGS_WITH_VARIANT_NAME; use rustc_session::lint::builtin::{IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS}; use rustc_session::parse::feature_err; use rustc_session::Session; -use rustc_span::{sym, Span}; +use rustc_span::{sym, SpanId}; use std::slice; crate fn check_match(tcx: TyCtxt<'_>, def_id: DefId) { @@ -34,7 +34,7 @@ crate fn check_match(tcx: TyCtxt<'_>, def_id: DefId) { visitor.visit_body(tcx.hir().body(body_id)); } -fn create_e0004(sess: &Session, sp: Span, error_message: String) -> DiagnosticBuilder<'_> { +fn create_e0004(sess: &Session, sp: SpanId, error_message: String) -> DiagnosticBuilder<'_> { struct_span_err!(sess, sp, E0004, "{}", &error_message) } @@ -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(loc.span.into())), hir::LocalSource::ForLoopDesugar => ("`for` loop binding", None), hir::LocalSource::AsyncFn => ("async fn binding", None), hir::LocalSource::AwaitDesugar => ("`await` future binding", None), @@ -81,7 +81,7 @@ impl<'tcx> Visitor<'tcx> for MatchVisitor<'_, 'tcx> { } impl PatCtxt<'_, '_> { - fn report_inlining_errors(&self, pat_span: Span) { + fn report_inlining_errors(&self, pat_span: SpanId) { for error in &self.errors { match *error { PatternError::StaticInPattern(span) => { @@ -112,7 +112,7 @@ impl PatCtxt<'_, '_> { } } - fn span_e0158(&self, span: Span, text: &str) { + fn span_e0158(&self, span: SpanId, text: &str) { struct_span_err!(self.tcx.sess, span, E0158, "{}", text).emit(); } } @@ -142,7 +142,7 @@ 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); + patcx.report_inlining_errors(pat.span.into()); } (pattern, pattern_ty) } @@ -191,10 +191,17 @@ impl<'tcx> MatchVisitor<'_, 'tcx> { // Note: An empty match isn't the same as an empty matrix for diagnostics purposes, // since an empty matrix can occur when there are arms, if those arms all have guards. let is_empty_match = inlined_arms.is_empty(); - check_exhaustive(&mut cx, scrut_ty, scrut.span, &matrix, scrut.hir_id, is_empty_match); + check_exhaustive( + &mut cx, + scrut_ty, + scrut.span.into(), + &matrix, + scrut.hir_id, + is_empty_match, + ); } - fn check_irrefutable(&self, pat: &'tcx Pat<'tcx>, origin: &str, sp: Option) { + fn check_irrefutable(&self, pat: &'tcx Pat<'tcx>, origin: &str, sp: Option) { let mut cx = self.new_cx(pat.hir_id); let (pattern, pattern_ty) = self.lower_pattern(&mut cx, pat, &mut false); @@ -232,7 +239,9 @@ impl<'tcx> MatchVisitor<'_, 'tcx> { "`let` bindings require an \"irrefutable pattern\", like a `struct` or \ an `enum` with only one variant", ); - if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { + if let Ok(snippet) = + self.tcx.sess.source_map().span_to_snippet(self.tcx.reify_span(span)) + { err.span_suggestion( span, "you might want to use `if let` to ignore the variant that isn't matched", @@ -333,7 +342,7 @@ fn pat_is_catchall(pat: &super::Pat<'_>) -> bool { } } -fn unreachable_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, catchall: Option) { +fn unreachable_pattern(tcx: TyCtxt<'_>, span: SpanId, id: HirId, catchall: Option) { tcx.struct_span_lint_hir(UNREACHABLE_PATTERNS, id, span, |lint| { let mut err = lint.build("unreachable pattern"); if let Some(catchall) = catchall { @@ -345,7 +354,7 @@ fn unreachable_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, catchall: Option< }); } -fn irrefutable_let_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, source: hir::MatchSource) { +fn irrefutable_let_pattern(tcx: TyCtxt<'_>, span: SpanId, id: HirId, source: hir::MatchSource) { tcx.struct_span_lint_hir(IRREFUTABLE_LET_PATTERNS, id, span, |lint| { let msg = match source { hir::MatchSource::IfLetDesugar { .. } => "irrefutable if-let pattern", @@ -433,7 +442,7 @@ fn check_not_useful<'p, 'tcx>( fn check_exhaustive<'p, 'tcx>( cx: &mut MatchCheckCtxt<'p, 'tcx>, scrut_ty: Ty<'tcx>, - sp: Span, + sp: SpanId, matrix: &Matrix<'p, 'tcx>, hir_id: HirId, is_empty_match: bool, @@ -535,7 +544,7 @@ fn adt_defined_here( } } -fn maybe_point_at_variant(ty: Ty<'_>, patterns: &[super::Pat<'_>]) -> Vec { +fn maybe_point_at_variant(ty: Ty<'_>, patterns: &[super::Pat<'_>]) -> Vec { let mut covered = vec![]; if let ty::Adt(def, _) = ty.kind { // Don't point at variants that have already been covered due to other patterns to avoid @@ -548,10 +557,10 @@ fn maybe_point_at_variant(ty: Ty<'_>, patterns: &[super::Pat<'_>]) -> Vec } Variant { adt_def, variant_index, subpatterns, .. } if adt_def.did == def.did => { let sp = def.variants[*variant_index].ident.span; - if covered.contains(&sp) { + if covered.contains(&sp.into()) { continue; } - covered.push(sp); + covered.push(sp.into()); let pats = subpatterns .iter() @@ -578,8 +587,8 @@ fn maybe_point_at_variant(ty: Ty<'_>, patterns: &[super::Pat<'_>]) -> Vec } /// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`. -fn is_binding_by_move(cx: &MatchVisitor<'_, '_>, hir_id: HirId, span: Span) -> bool { - !cx.tables.node_type(hir_id).is_copy_modulo_regions(cx.tcx, cx.param_env, span) +fn is_binding_by_move(cx: &MatchVisitor<'_, '_>, hir_id: HirId, span: SpanId) -> bool { + !cx.tables.node_type(hir_id).is_copy_modulo_regions(cx.tcx, cx.param_env, span.into()) } /// Check the legality of legality of by-move bindings. @@ -612,7 +621,7 @@ fn check_legality_of_move_bindings(cx: &mut MatchVisitor<'_, '_>, has_guard: boo 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) { + if is_binding_by_move(cx, p.hir_id, p.span.into()) { check_move(p, sub.as_deref()); } } @@ -660,7 +669,7 @@ fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_ // 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) => { + Some(ty::BindByValue(_)) if is_binding_by_move(cx, pat.hir_id, pat.span.into()) => { // 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, _| { @@ -699,7 +708,7 @@ fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_ (Mutability::Mut, Mutability::Mut) => conflicts_mut_mut.push((span, name)), // 2x `ref mut`. _ => conflicts_mut_ref.push((span, name)), // `ref` + `ref mut` in either direction. }, - Some(ty::BindByValue(_)) if is_binding_by_move(cx, hir_id, span) => { + Some(ty::BindByValue(_)) if is_binding_by_move(cx, hir_id, span.into()) => { conflicts_move.push((span, name)) // `ref mut?` + by-move conflict. } Some(ty::BindByValue(_)) | None => {} // `ref mut?` + by-copy is fine. diff --git a/src/librustc_mir_build/hair/pattern/const_to_pat.rs b/src/librustc_mir_build/hair/pattern/const_to_pat.rs index 854f8eeaf3441..598b135968d27 100644 --- a/src/librustc_mir_build/hair/pattern/const_to_pat.rs +++ b/src/librustc_mir_build/hair/pattern/const_to_pat.rs @@ -4,7 +4,7 @@ use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; use rustc_middle::mir::Field; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_session::lint; -use rustc_span::Span; +use rustc_span::SpanId; use rustc_trait_selection::traits::predicate_for_trait_def; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligation}; @@ -21,7 +21,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { &self, cv: &'tcx ty::Const<'tcx>, id: hir::HirId, - span: Span, + span: SpanId, mir_structural_match_violation: bool, ) -> Pat<'tcx> { debug!("const_to_pat: cv={:#?} id={:?}", cv, id); @@ -36,7 +36,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { struct ConstToPat<'a, 'tcx> { id: hir::HirId, - span: Span, + span: SpanId, param_env: ty::ParamEnv<'tcx>, // This tracks if we signal some hard error for a given const value, so that @@ -54,7 +54,7 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> { fn new( pat_ctxt: &PatCtxt<'_, 'tcx>, id: hir::HirId, - span: Span, + span: SpanId, infcx: InferCtxt<'a, 'tcx>, ) -> Self { ConstToPat { @@ -75,11 +75,16 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> { &self, ty: Ty<'tcx>, ) -> Option> { - traits::search_for_structural_match_violation(self.id, self.span, self.tcx(), ty) + traits::search_for_structural_match_violation( + self.id, + self.tcx().reify_span(self.span), + self.tcx(), + ty, + ) } fn type_marked_structural(&self, ty: Ty<'tcx>) -> bool { - traits::type_marked_structural(self.id, self.span, &self.infcx, ty) + traits::type_marked_structural(self.id, self.tcx().reify_span(self.span), &self.infcx, ty) } fn to_pat( @@ -144,7 +149,7 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> { let obligation: PredicateObligation<'_> = predicate_for_trait_def( self.tcx(), self.param_env, - ObligationCause::misc(self.span, self.id), + ObligationCause::misc(self.tcx().reify_span(self.span), self.id), partial_eq_trait_id, 0, cv.ty, diff --git a/src/librustc_mir_build/hair/pattern/mod.rs b/src/librustc_mir_build/hair/pattern/mod.rs index e9aa7f597beb6..e6789fc118b34 100644 --- a/src/librustc_mir_build/hair/pattern/mod.rs +++ b/src/librustc_mir_build/hair/pattern/mod.rs @@ -24,7 +24,7 @@ use rustc_middle::ty::{self, AdtDef, DefIdTree, Region, Ty, TyCtxt, UserType}; use rustc_middle::ty::{ CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, }; -use rustc_span::{Span, Symbol, DUMMY_SP}; +use rustc_span::{SpanId, Symbol, DUMMY_SPID}; use rustc_target::abi::VariantIdx; use std::cmp::Ordering; @@ -32,11 +32,11 @@ use std::fmt; #[derive(Clone, Debug)] crate enum PatternError { - AssocConstInPattern(Span), - ConstParamInPattern(Span), - StaticInPattern(Span), + AssocConstInPattern(SpanId), + ConstParamInPattern(SpanId), + StaticInPattern(SpanId), FloatBug, - NonConstPath(Span), + NonConstPath(SpanId), } #[derive(Copy, Clone, Debug)] @@ -54,13 +54,13 @@ crate struct FieldPat<'tcx> { #[derive(Clone, Debug)] crate struct Pat<'tcx> { crate ty: Ty<'tcx>, - crate span: Span, + crate span: SpanId, crate kind: Box>, } impl<'tcx> Pat<'tcx> { pub(crate) fn wildcard_from_ty(ty: Ty<'tcx>) -> Self { - Pat { ty, span: DUMMY_SP, kind: Box::new(PatKind::Wild) } + Pat { ty, span: DUMMY_SPID, kind: Box::new(PatKind::Wild) } } } @@ -76,13 +76,14 @@ impl<'tcx> PatTyProj<'tcx> { pub(crate) fn user_ty( self, + tcx: TyCtxt<'tcx>, annotations: &mut CanonicalUserTypeAnnotations<'tcx>, inferred_ty: Ty<'tcx>, - span: Span, + span: SpanId, ) -> UserTypeProjection { UserTypeProjection { base: annotations.push(CanonicalUserTypeAnnotation { - span, + span: tcx.reify_span(span), user_ty: self.user_ty, inferred_ty, }), @@ -113,7 +114,7 @@ crate struct Ascription<'tcx> { /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior /// of the old type-check for now. See #57280 for details. crate variance: ty::Variance, - crate user_ty_span: Span, + crate user_ty_span: SpanId, } #[derive(Clone, Debug)] @@ -438,7 +439,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { lo: &'tcx ty::Const<'tcx>, hi: &'tcx ty::Const<'tcx>, end: RangeEnd, - span: Span, + span: SpanId, ) -> PatKind<'tcx> { assert_eq!(lo.ty, ty); assert_eq!(hi.ty, ty); @@ -511,7 +512,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { 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.into(), ty, kind: Box::new(PatKind::Wild) }; } let kind = match pat.kind { @@ -521,7 +522,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { hir::PatKind::Range(ref lo_expr, ref hi_expr, end) => { let (lo_expr, hi_expr) = (lo_expr.as_deref(), hi_expr.as_deref()); - let lo_span = lo_expr.map_or(pat.span, |e| e.span); + let lo_span = lo_expr.map_or(pat.span, |e| e.span).into(); let lo = lo_expr.map(|e| self.lower_range_expr(e)); let hi = hi_expr.map(|e| self.lower_range_expr(e)); @@ -543,7 +544,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { // constants somewhere. Have them on the range pattern. for end in &[lo, hi] { if let Some((_, Some(ascription))) = end { - let subpattern = Pat { span: pat.span, ty, kind: Box::new(kind) }; + let subpattern = Pat { span: pat.span.into(), ty, kind: Box::new(kind) }; kind = PatKind::AscribeUserType { ascription: *ascription, subpattern }; } } @@ -552,7 +553,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { } hir::PatKind::Path(ref qpath) => { - return self.lower_path(qpath, pat.hir_id, pat.span); + return self.lower_path(qpath, pat.hir_id, pat.span.into()); } hir::PatKind::Ref(ref subpattern, _) | hir::PatKind::Box(ref subpattern) => { @@ -560,7 +561,7 @@ 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.into(), ty, prefix, slice, suffix) } hir::PatKind::Tuple(ref pats, ddpos) => { @@ -616,7 +617,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { }; 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.into(), ty, subpatterns) } hir::PatKind::Struct(ref qpath, ref fields, _) => { @@ -629,13 +630,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.into(), 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.into(), ty, kind: Box::new(kind) } } fn lower_tuple_subpats( @@ -663,7 +664,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { fn slice_or_array_pattern( &mut self, - span: Span, + span: SpanId, ty: Ty<'tcx>, prefix: &'tcx [&'tcx hir::Pat<'tcx>], slice: &'tcx Option<&'tcx hir::Pat<'tcx>>, @@ -689,7 +690,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { &mut self, res: Res, hir_id: hir::HirId, - span: Span, + span: SpanId, ty: Ty<'tcx>, subpatterns: Vec>, ) -> PatKind<'tcx> { @@ -763,7 +764,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { /// Takes a HIR Path. If the path is a constant, evaluates it and feeds /// it to `const_to_pat`. Any other path (like enum variants without fields) /// is converted to the corresponding pattern via `lower_variant_or_leaf`. - fn lower_path(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, span: Span) -> Pat<'tcx> { + fn lower_path(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, span: SpanId) -> Pat<'tcx> { let ty = self.tables.node_type(id); let res = self.tables.qpath_res(qpath, id); @@ -804,7 +805,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { let mir_structural_match_violation = self.tcx.mir_const_qualif(instance.def_id()).custom_eq; debug!("mir_structural_match_violation({:?}) -> {}", qpath, mir_structural_match_violation); - match self.tcx.const_eval_instance(param_env_reveal_all, instance, Some(span)) { + match self.tcx.const_eval_instance(param_env_reveal_all, instance, Some(span.into())) { Ok(value) => { let const_ = ty::Const::from_value(self.tcx, value, self.tables.node_type(id)); @@ -848,7 +849,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { /// afterwards. fn lower_lit(&mut self, expr: &'tcx hir::Expr<'tcx>) -> PatKind<'tcx> { if let hir::ExprKind::Path(ref qpath) = expr.kind { - *self.lower_path(qpath, expr.hir_id, expr.span).kind + *self.lower_path(qpath, expr.hir_id, expr.span.into()).kind } else { let (lit, neg) = match expr.kind { hir::ExprKind::Lit(ref lit) => (lit, false), @@ -864,7 +865,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { let lit_input = LitToConstInput { lit: &lit.node, ty: self.tables.expr_ty(expr), neg }; match self.tcx.at(expr.span).lit_to_const(lit_input) { - Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span, false).kind, + Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span.into(), false).kind, Err(LitToConstError::UnparseableFloat) => { self.errors.push(PatternError::FloatBug); PatKind::Wild @@ -936,7 +937,7 @@ macro_rules! CloneImpls { } CloneImpls! { <'tcx> - Span, Field, Mutability, Symbol, hir::HirId, usize, ty::Const<'tcx>, + SpanId, Field, Mutability, Symbol, hir::HirId, usize, ty::Const<'tcx>, Region<'tcx>, Ty<'tcx>, BindingMode, &'tcx AdtDef, SubstsRef<'tcx>, &'tcx GenericArg<'tcx>, UserType<'tcx>, UserTypeProjection, PatTyProj<'tcx> diff --git a/src/librustc_mir_build/lints.rs b/src/librustc_mir_build/lints.rs index 69bfad6b13999..9216729d1483f 100644 --- a/src/librustc_mir_build/lints.rs +++ b/src/librustc_mir_build/lints.rs @@ -8,7 +8,7 @@ use rustc_middle::mir::{BasicBlock, Body, Operand, TerminatorKind}; use rustc_middle::ty::subst::{GenericArg, InternalSubsts}; use rustc_middle::ty::{self, AssocItem, AssocItemContainer, Instance, TyCtxt}; use rustc_session::lint::builtin::UNCONDITIONAL_RECURSION; -use rustc_span::Span; +use rustc_span::SpanId; crate fn check<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, def_id: LocalDefId) { let hir_id = tcx.hir().as_local_hir_id(def_id); @@ -60,7 +60,7 @@ struct Search<'mir, 'tcx> { def_id: LocalDefId, trait_substs: &'tcx [GenericArg<'tcx>], - reachable_recursive_calls: Vec, + reachable_recursive_calls: Vec, } impl<'mir, 'tcx> Search<'mir, 'tcx> { diff --git a/src/librustc_parse/lib.rs b/src/librustc_parse/lib.rs index 8e2a9513d6b82..11c8260a05e06 100644 --- a/src/librustc_parse/lib.rs +++ b/src/librustc_parse/lib.rs @@ -42,7 +42,7 @@ macro_rules! panictry_buffer { Ok(e) => e, Err(errs) => { for e in errs { - $handler.emit_diagnostic(&e); + $handler.emit_diagnostic(e); } FatalError.raise() } @@ -176,7 +176,7 @@ fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option) -> match try_file_to_source_file(sess, path, spanopt) { Ok(source_file) => source_file, Err(d) => { - sess.span_diagnostic.emit_diagnostic(&d); + sess.span_diagnostic.emit_diagnostic(d); FatalError.raise(); } } diff --git a/src/librustc_parse/parser/diagnostics.rs b/src/librustc_parse/parser/diagnostics.rs index 437d0ffa1196d..480bb1d90b0ef 100644 --- a/src/librustc_parse/parser/diagnostics.rs +++ b/src/librustc_parse/parser/diagnostics.rs @@ -12,7 +12,7 @@ use rustc_errors::{pluralize, struct_span_err}; use rustc_errors::{Applicability, DiagnosticBuilder, Handler, PResult}; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, Ident}; -use rustc_span::{MultiSpan, Span, SpanSnippetError, DUMMY_SP}; +use rustc_span::{MultiSpanId, Span, SpanSnippetError, DUMMY_SP}; use log::{debug, trace}; @@ -41,7 +41,7 @@ pub enum Error { } impl Error { - fn span_err(self, sp: impl Into, handler: &Handler) -> DiagnosticBuilder<'_> { + fn span_err(self, sp: impl Into, handler: &Handler) -> DiagnosticBuilder<'_> { match self { Error::UselessDocComment => { let mut err = struct_span_err!( @@ -106,7 +106,7 @@ crate enum ConsumeClosingDelim { } impl<'a> Parser<'a> { - pub(super) fn span_fatal_err>( + pub(super) fn span_fatal_err>( &self, sp: S, err: Error, @@ -114,11 +114,11 @@ impl<'a> Parser<'a> { err.span_err(sp, self.diagnostic()) } - pub fn struct_span_err>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> { + pub fn struct_span_err>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> { self.sess.span_diagnostic.struct_span_err(sp, m) } - pub fn span_bug>(&self, sp: S, m: &str) -> ! { + pub fn span_bug>(&self, sp: S, m: &str) -> ! { self.sess.span_diagnostic.span_bug(sp, m) } diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 917e2f548302f..32b6127e580db 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -340,7 +340,7 @@ fn def_id_visibility<'tcx>( None => { let vis = tcx.visibility(def_id); let descr = if vis == ty::Visibility::Public { "public" } else { "private" }; - (vis, tcx.def_span(def_id), descr) + (vis, tcx.real_def_span(def_id), descr) } } } diff --git a/src/librustc_query_system/dep_graph/graph.rs b/src/librustc_query_system/dep_graph/graph.rs index 5f14a09b24daa..7a895b0855516 100644 --- a/src/librustc_query_system/dep_graph/graph.rs +++ b/src/librustc_query_system/dep_graph/graph.rs @@ -763,7 +763,7 @@ impl DepGraph { let handle = tcx.diagnostic(); for diagnostic in diagnostics { - handle.emit_diagnostic(&diagnostic); + handle.emit_diagnostic(diagnostic); } // Mark the node as green now that diagnostics are emitted diff --git a/src/librustc_query_system/query/job.rs b/src/librustc_query_system/query/job.rs index 5150b278a7722..3baea8ef7a4a2 100644 --- a/src/librustc_query_system/query/job.rs +++ b/src/librustc_query_system/query/job.rs @@ -3,7 +3,7 @@ use crate::query::plumbing::CycleError; use crate::query::QueryContext; use rustc_data_structures::fx::FxHashMap; -use rustc_span::Span; +use rustc_span::SpanId; use std::convert::TryFrom; use std::marker::PhantomData; @@ -18,7 +18,7 @@ use { rustc_data_structures::sync::Lrc, rustc_data_structures::{jobserver, OnDrop}, rustc_rayon_core as rayon_core, - rustc_span::DUMMY_SP, + rustc_span::DUMMY_SPID, std::iter::FromIterator, std::{mem, process}, }; @@ -27,7 +27,7 @@ use { #[derive(Clone, Debug)] pub struct QueryInfo { /// The span corresponding to the reason for which this query was required. - pub span: Span, + pub span: SpanId, pub query: Q, } @@ -60,7 +60,7 @@ impl QueryJobId { } #[cfg(parallel_compiler)] - fn span>(self, map: &QueryMap) -> Span { + fn span>(self, map: &QueryMap) -> SpanId { map.get(&self).unwrap().job.span } @@ -89,7 +89,7 @@ pub struct QueryJob { pub id: QueryShardJobId, /// The span corresponding to the reason for which this query was required. - pub span: Span, + pub span: SpanId, /// The parent query job which created this job and is implicitly waiting on it. pub parent: Option>, @@ -103,7 +103,11 @@ pub struct QueryJob { impl QueryJob { /// Creates a new query job. - pub fn new(id: QueryShardJobId, span: Span, parent: Option>) -> Self { + pub fn new( + id: QueryShardJobId, + span: SpanId, + parent: Option>, + ) -> Self { QueryJob { id, span, @@ -150,7 +154,7 @@ pub(super) struct QueryLatch { #[cfg(not(parallel_compiler))] impl QueryLatch { - pub(super) fn find_cycle_in_stack(&self, tcx: CTX, span: Span) -> CycleError { + pub(super) fn find_cycle_in_stack(&self, tcx: CTX, span: SpanId) -> CycleError { let query_map = tcx.try_collect_active_jobs().unwrap(); // Get the current executing query (waiter) and find the waitee amongst its parents @@ -189,7 +193,7 @@ impl QueryLatch { struct QueryWaiter { query: Option>, condvar: Condvar, - span: Span, + span: SpanId, cycle: Lock>>, } @@ -225,7 +229,7 @@ impl QueryLatch { #[cfg(parallel_compiler)] impl QueryLatch { /// Awaits for the query job to complete. - pub(super) fn wait_on(&self, tcx: CTX, span: Span) -> Result<(), CycleError> { + pub(super) fn wait_on(&self, tcx: CTX, span: SpanId) -> Result<(), CycleError> { let query = tcx.current_query_job(); let waiter = Lrc::new(QueryWaiter { query, span, cycle: Lock::new(None), condvar: Condvar::new() }); @@ -306,7 +310,7 @@ fn visit_waiters( mut visit: F, ) -> Option>> where - F: FnMut(Span, QueryJobId) -> Option>>, + F: FnMut(SpanId, QueryJobId) -> Option>>, { // Visit the parent query which is a non-resumable waiter since it's on the same stack if let Some(parent) = query.parent(query_map) { @@ -338,8 +342,8 @@ where fn cycle_check( query_map: &QueryMap, query: QueryJobId, - span: Span, - stack: &mut Vec<(Span, QueryJobId)>, + span: SpanId, + stack: &mut Vec<(SpanId, QueryJobId)>, visited: &mut FxHashSet>, ) -> Option>> { if !visited.insert(query) { @@ -402,7 +406,7 @@ fn connected_to_root( fn pick_query<'a, CTX, T, F>(query_map: &QueryMap, tcx: CTX, queries: &'a [T], f: F) -> &'a T where CTX: QueryContext, - F: Fn(&T) -> (Span, QueryJobId), + F: Fn(&T) -> (SpanId, QueryJobId), { // Deterministically pick an entry point // FIXME: Sort this instead @@ -416,7 +420,7 @@ where // Prefer entry points which have valid spans for nicer error messages // We add an integer to the tuple ensuring that entry points // with valid spans are picked first - let span_cmp = if span == DUMMY_SP { 1 } else { 0 }; + let span_cmp = if span == DUMMY_SPID { 1 } else { 0 }; (span_cmp, stable_hasher.finish::()) }) .unwrap() @@ -438,7 +442,7 @@ fn remove_cycle( let mut stack = Vec::new(); // Look for a cycle starting with the last query in `jobs` if let Some(waiter) = - cycle_check(query_map, jobs.pop().unwrap(), DUMMY_SP, &mut stack, &mut visited) + cycle_check(query_map, jobs.pop().unwrap(), DUMMY_SPID, &mut stack, &mut visited) { // The stack is a vector of pairs of spans and queries; reverse it so that // the earlier entries require later entries @@ -485,7 +489,7 @@ fn remove_cycle( } } }) - .collect::, Option<(Span, QueryJobId)>)>>(); + .collect::, Option<(SpanId, QueryJobId)>)>>(); // Deterministically pick an entry point let (_, entry_point, usage) = pick_query(query_map, tcx, &entry_points, |e| (e.0, e.1)); diff --git a/src/librustc_query_system/query/plumbing.rs b/src/librustc_query_system/query/plumbing.rs index cc7d0a1570355..b77815872b030 100644 --- a/src/librustc_query_system/query/plumbing.rs +++ b/src/librustc_query_system/query/plumbing.rs @@ -17,8 +17,7 @@ use rustc_data_structures::sharded::Sharded; use rustc_data_structures::sync::{Lock, LockGuard}; use rustc_data_structures::thin_vec::ThinVec; use rustc_errors::{Diagnostic, FatalError}; -use rustc_span::source_map::DUMMY_SP; -use rustc_span::Span; +use rustc_span::{SpanId, DUMMY_SPID}; use std::collections::hash_map::Entry; use std::convert::TryFrom; use std::fmt::Debug; @@ -173,7 +172,7 @@ where fn try_start<'a, 'b>( tcx: CTX, state: &'b QueryState, - span: Span, + span: SpanId, key: &C::Key, mut lookup: QueryLookup<'a, CTX, C::Key, C::Sharded>, query: &QueryVtable, @@ -325,7 +324,7 @@ where #[derive(Clone)] pub struct CycleError { /// The query and related span that uses the cycle. - pub usage: Option<(Span, Q)>, + pub usage: Option<(SpanId, Q)>, pub cycle: Vec>, } @@ -387,7 +386,7 @@ where fn try_execute_query( tcx: CTX, state: &QueryState, - span: Span, + span: SpanId, key: C::Key, lookup: QueryLookup<'_, CTX, C::Key, C::Sharded>, query: &QueryVtable, @@ -618,7 +617,7 @@ where fn get_query_impl( tcx: CTX, state: &QueryState, - span: Span, + span: SpanId, key: C::Key, query: &QueryVtable, ) -> C::Stored @@ -659,7 +658,7 @@ fn ensure_query_impl( CTX: QueryContext, { if query.eval_always { - let _ = get_query_impl(tcx, state, DUMMY_SP, key, query); + let _ = get_query_impl(tcx, state, DUMMY_SPID, key, query); return; } @@ -676,7 +675,7 @@ fn ensure_query_impl( // DepNodeIndex. We must invoke the query itself. The performance cost // this introduces should be negligible as we'll immediately hit the // in-memory cache, or another query down the line will. - let _ = get_query_impl(tcx, state, DUMMY_SP, key, query); + let _ = get_query_impl(tcx, state, DUMMY_SPID, key, query); } Some((_, dep_node_index)) => { tcx.profiler().query_cache_hit(dep_node_index.into()); @@ -689,7 +688,7 @@ fn force_query_impl( tcx: CTX, state: &QueryState, key: C::Key, - span: Span, + span: SpanId, dep_node: DepNode, query: &QueryVtable, ) where @@ -720,7 +719,7 @@ fn force_query_impl( } #[inline(always)] -pub fn get_query(tcx: CTX, span: Span, key: Q::Key) -> Q::Stored +pub fn get_query(tcx: CTX, span: SpanId, key: Q::Key) -> Q::Stored where Q: QueryDescription, Q::Key: crate::dep_graph::DepNodeParams, @@ -742,7 +741,7 @@ where } #[inline(always)] -pub fn force_query(tcx: CTX, key: Q::Key, span: Span, dep_node: DepNode) +pub fn force_query(tcx: CTX, key: Q::Key, span: SpanId, dep_node: DepNode) where Q: QueryDescription, Q::Key: crate::dep_graph::DepNodeParams, diff --git a/src/librustc_resolve/imports.rs b/src/librustc_resolve/imports.rs index a1e05d21b58d5..a51e26ffc1007 100644 --- a/src/librustc_resolve/imports.rs +++ b/src/librustc_resolve/imports.rs @@ -1414,7 +1414,7 @@ impl<'a, 'b> ImportResolver<'a, 'b> { .to_owned(); let error_id = ( DiagnosticMessageId::ErrorId(0), // no code?! - Some(binding.span), + Some(binding.span.into()), msg.clone(), ); let fresh = diff --git a/src/librustc_session/lint.rs b/src/librustc_session/lint.rs index b16d513d9239f..8e1f4217f5295 100644 --- a/src/librustc_session/lint.rs +++ b/src/librustc_session/lint.rs @@ -3,7 +3,7 @@ use rustc_ast::node_id::{NodeId, NodeMap}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey}; use rustc_errors::{pluralize, Applicability, DiagnosticBuilder}; use rustc_span::edition::Edition; -use rustc_span::{sym, symbol::Ident, MultiSpan, Span, Symbol}; +use rustc_span::{sym, symbol::Ident, MultiSpanId, Span, Symbol}; pub mod builtin; @@ -199,7 +199,7 @@ pub enum BuiltinLintDiagnostics { #[derive(PartialEq)] pub struct BufferedEarlyLint { /// The span of code that we are linting on. - pub span: MultiSpan, + pub span: MultiSpanId, /// The lint message. pub msg: String, @@ -232,7 +232,7 @@ impl LintBuffer { &mut self, lint: &'static Lint, node_id: NodeId, - span: MultiSpan, + span: MultiSpanId, msg: &str, diagnostic: BuiltinLintDiagnostics, ) { @@ -249,7 +249,7 @@ impl LintBuffer { &mut self, lint: &'static Lint, id: NodeId, - sp: impl Into, + sp: impl Into, msg: &str, ) { self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal) @@ -259,7 +259,7 @@ impl LintBuffer { &mut self, lint: &'static Lint, id: NodeId, - sp: impl Into, + sp: impl Into, msg: &str, diagnostic: BuiltinLintDiagnostics, ) { diff --git a/src/librustc_session/parse.rs b/src/librustc_session/parse.rs index 69d3e99b7458e..0d96dca23c212 100644 --- a/src/librustc_session/parse.rs +++ b/src/librustc_session/parse.rs @@ -11,7 +11,7 @@ use rustc_feature::{find_feature_issue, GateIssue, UnstableFeatures}; use rustc_span::edition::Edition; use rustc_span::hygiene::ExpnId; use rustc_span::source_map::{FilePathMapping, SourceMap}; -use rustc_span::{MultiSpan, Span, Symbol}; +use rustc_span::{MultiSpanId, Span, Symbol}; use std::path::PathBuf; use std::str; @@ -79,7 +79,7 @@ impl SymbolGallery { pub fn feature_err<'a>( sess: &'a ParseSess, feature: Symbol, - span: impl Into, + span: impl Into, explain: &str, ) -> DiagnosticBuilder<'a> { feature_err_issue(sess, feature, span, GateIssue::Language, explain) @@ -92,7 +92,7 @@ pub fn feature_err<'a>( pub fn feature_err_issue<'a>( sess: &'a ParseSess, feature: Symbol, - span: impl Into, + span: impl Into, issue: GateIssue, explain: &str, ) -> DiagnosticBuilder<'a> { @@ -177,7 +177,7 @@ impl ParseSess { pub fn buffer_lint( &self, lint: &'static Lint, - span: impl Into, + span: impl Into, node_id: NodeId, msg: &str, ) { @@ -195,7 +195,7 @@ impl ParseSess { pub fn buffer_lint_with_diagnostic( &self, lint: &'static Lint, - span: impl Into, + span: impl Into, node_id: NodeId, msg: &str, diagnostic: BuiltinLintDiagnostics, diff --git a/src/librustc_session/session.rs b/src/librustc_session/session.rs index b39b15dc24428..6d7b24121bfbc 100644 --- a/src/librustc_session/session.rs +++ b/src/librustc_session/session.rs @@ -21,7 +21,9 @@ use rustc_errors::json::JsonEmitter; use rustc_errors::registry::Registry; use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticId, ErrorReported}; use rustc_span::edition::Edition; -use rustc_span::source_map::{self, FileLoader, MultiSpan, RealFileLoader, SourceMap, Span}; +use rustc_span::source_map::{ + self, FileLoader, MultiSpanId, RealFileLoader, SourceMap, Span, SpanId, +}; use rustc_span::{SourceFileHashAlgorithm, Symbol}; use rustc_target::spec::{PanicStrategy, RelocModel, RelroLevel, Target, TargetTriple, TlsModel}; @@ -73,7 +75,7 @@ pub struct Session { /// Set of `(DiagnosticId, Option, message)` tuples tracking /// (sub)diagnostics that have been set once, but should not be set again, /// in order to avoid redundantly verbose output (Issue #24690, #44953). - pub one_time_diagnostics: Lock, String)>>, + pub one_time_diagnostics: Lock, String)>>, pub crate_types: Once>, /// The `crate_disambiguator` is constructed out of all the `-C metadata` /// arguments passed to the compiler. Its value together with the crate-name @@ -238,10 +240,14 @@ impl Session { *self.crate_disambiguator.get() } - pub fn struct_span_warn>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> { + pub fn struct_span_warn>( + &self, + sp: S, + msg: &str, + ) -> DiagnosticBuilder<'_> { self.diagnostic().struct_span_warn(sp, msg) } - pub fn struct_span_warn_with_code>( + pub fn struct_span_warn_with_code>( &self, sp: S, msg: &str, @@ -252,10 +258,10 @@ impl Session { pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> { self.diagnostic().struct_warn(msg) } - pub fn struct_span_err>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> { + pub fn struct_span_err>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> { self.diagnostic().struct_span_err(sp, msg) } - pub fn struct_span_err_with_code>( + pub fn struct_span_err_with_code>( &self, sp: S, msg: &str, @@ -270,10 +276,14 @@ impl Session { pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> { self.diagnostic().struct_err_with_code(msg, code) } - pub fn struct_span_fatal>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> { + pub fn struct_span_fatal>( + &self, + sp: S, + msg: &str, + ) -> DiagnosticBuilder<'_> { self.diagnostic().struct_span_fatal(sp, msg) } - pub fn struct_span_fatal_with_code>( + pub fn struct_span_fatal_with_code>( &self, sp: S, msg: &str, @@ -285,10 +295,10 @@ impl Session { self.diagnostic().struct_fatal(msg) } - pub fn span_fatal>(&self, sp: S, msg: &str) -> ! { + pub fn span_fatal>(&self, sp: S, msg: &str) -> ! { self.diagnostic().span_fatal(sp, msg).raise() } - pub fn span_fatal_with_code>( + pub fn span_fatal_with_code>( &self, sp: S, msg: &str, @@ -299,17 +309,17 @@ impl Session { pub fn fatal(&self, msg: &str) -> ! { self.diagnostic().fatal(msg).raise() } - pub fn span_err_or_warn>(&self, is_warning: bool, sp: S, msg: &str) { + pub fn span_err_or_warn>(&self, is_warning: bool, sp: S, msg: &str) { if is_warning { self.span_warn(sp, msg); } else { self.span_err(sp, msg); } } - pub fn span_err>(&self, sp: S, msg: &str) { + pub fn span_err>(&self, sp: S, msg: &str) { self.diagnostic().span_err(sp, msg) } - pub fn span_err_with_code>(&self, sp: S, msg: &str, code: DiagnosticId) { + pub fn span_err_with_code>(&self, sp: S, msg: &str, code: DiagnosticId) { self.diagnostic().span_err_with_code(sp, &msg, code) } pub fn err(&self, msg: &str) { @@ -345,29 +355,29 @@ impl Session { let errors = self.err_count() - old_count; if errors == 0 { Ok(result) } else { Err(ErrorReported) } } - pub fn span_warn>(&self, sp: S, msg: &str) { + pub fn span_warn>(&self, sp: S, msg: &str) { self.diagnostic().span_warn(sp, msg) } - pub fn span_warn_with_code>(&self, sp: S, msg: &str, code: DiagnosticId) { + pub fn span_warn_with_code>(&self, sp: S, msg: &str, code: DiagnosticId) { self.diagnostic().span_warn_with_code(sp, msg, code) } pub fn warn(&self, msg: &str) { self.diagnostic().warn(msg) } - pub fn opt_span_warn>(&self, opt_sp: Option, msg: &str) { + pub fn opt_span_warn>(&self, opt_sp: Option, msg: &str) { match opt_sp { Some(sp) => self.span_warn(sp, msg), None => self.warn(msg), } } /// Delay a span_bug() call until abort_if_errors() - pub fn delay_span_bug>(&self, sp: S, msg: &str) { + pub fn delay_span_bug>(&self, sp: S, msg: &str) { self.diagnostic().delay_span_bug(sp, msg) } pub fn note_without_error(&self, msg: &str) { self.diagnostic().note_without_error(msg) } - pub fn span_note_without_error>(&self, sp: S, msg: &str) { + pub fn span_note_without_error>(&self, sp: S, msg: &str) { self.diagnostic().span_note_without_error(sp, msg) } @@ -383,7 +393,7 @@ impl Session { method: DiagnosticBuilderMethod, msg_id: DiagnosticMessageId, message: &str, - span_maybe: Option, + span_maybe: Option, ) { let id_span_message = (msg_id, span_maybe, message.to_owned()); let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message); @@ -413,7 +423,7 @@ impl Session { &'a self, diag_builder: &'b mut DiagnosticBuilder<'a>, msg_id: DiagnosticMessageId, - span: Span, + span: impl Into, message: &str, ) { self.diag_once( @@ -421,7 +431,7 @@ impl Session { DiagnosticBuilderMethod::SpanNote, msg_id, message, - Some(span), + Some(span.into()), ); } @@ -438,7 +448,7 @@ impl Session { &'a self, diag_builder: &'b mut DiagnosticBuilder<'a>, msg_id: DiagnosticMessageId, - span: Span, + span: impl Into, message: &str, suggestion: String, ) { @@ -447,7 +457,7 @@ impl Session { DiagnosticBuilderMethod::SpanSuggestion(suggestion), msg_id, message, - Some(span), + Some(span.into()), ); } diff --git a/src/librustc_span/lib.rs b/src/librustc_span/lib.rs index 58cdb87158afe..91d35265a2d10 100644 --- a/src/librustc_span/lib.rs +++ b/src/librustc_span/lib.rs @@ -239,6 +239,54 @@ impl Ord for Span { } } +#[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)] +#[derive(HashStable_Generic)] +pub enum SpanId { + Span(Span), + DefId(DefId), +} + +pub const DUMMY_SPID: SpanId = SpanId::Span(DUMMY_SP); + +impl Default for SpanId { + fn default() -> SpanId { + SpanId::Span(DUMMY_SP) + } +} + +impl From for SpanId { + fn from(span: Span) -> SpanId { + SpanId::Span(span) + } +} + +impl SpanId { + pub fn is_dummy(self) -> bool { + match self { + SpanId::Span(sp) => sp.is_dummy(), + _ => false, + } + } +} + +pub trait SpanLike: + Copy + Clone + std::fmt::Debug + Hash + PartialEq + Eq + PartialOrd + Ord + Default +{ + fn is_dummy(&self) -> bool; +} + +impl SpanLike for Span { + fn is_dummy(&self) -> bool { + Span::is_dummy(*self) + } +} + +impl SpanLike for SpanId { + fn is_dummy(&self) -> bool { + SpanId::is_dummy(*self) + } +} + /// A collection of spans. Spans have two orthogonal attributes: /// /// - They can be *primary spans*. In this case they are the locus of @@ -246,11 +294,14 @@ impl Ord for Span { /// - They can have a *label*. In this case, the label is written next /// to the mark in the snippet when we render. #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] -pub struct MultiSpan { +pub struct Multi { primary_spans: Vec, span_labels: Vec<(Span, String)>, } +pub type MultiSpan = Multi; +pub type MultiSpanId = Multi; + impl Span { #[inline] pub fn lo(self) -> BytePos { @@ -592,7 +643,7 @@ impl Span { } #[derive(Clone, Debug)] -pub struct SpanLabel { +pub struct Labelled { /// The span we are going to include in the final snippet. pub span: Span, @@ -604,6 +655,9 @@ pub struct SpanLabel { pub label: Option, } +pub type SpanLabel = Labelled; +pub type SpanIdLabel = Labelled; + impl Default for Span { fn default() -> Self { DUMMY_SP @@ -631,39 +685,49 @@ impl rustc_serialize::UseSpecializedDecodable for Span { } } -pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Span") - .field("lo", &span.lo()) - .field("hi", &span.hi()) - .field("ctxt", &span.ctxt()) - .finish() +pub fn default_span_debug(span: SpanId, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match span { + SpanId::Span(span) => f + .debug_struct("Span") + .field("lo", &span.lo()) + .field("hi", &span.hi()) + .field("ctxt", &span.ctxt()) + .finish(), + SpanId::DefId(did) => f.debug_tuple("DefId").field(&did).finish(), + } } impl fmt::Debug for Span { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - (*SPAN_DEBUG)(*self, f) + (*SPAN_DEBUG)(SpanId::Span(*self), f) } } impl fmt::Debug for SpanData { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f) + (*SPAN_DEBUG)(SpanId::Span(Span::new(self.lo, self.hi, self.ctxt)), f) + } +} + +impl fmt::Debug for SpanId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + (*SPAN_DEBUG)(*self, f) } } -impl MultiSpan { +impl Multi { #[inline] - pub fn new() -> MultiSpan { - MultiSpan { primary_spans: vec![], span_labels: vec![] } + pub fn new() -> Self { + Self { primary_spans: vec![], span_labels: vec![] } } - pub fn from_span(primary_span: Span) -> MultiSpan { - MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } + pub fn from_span(primary_span: impl Into) -> Self { + Self { primary_spans: vec![primary_span.into()], span_labels: vec![] } } - pub fn from_spans(mut vec: Vec) -> MultiSpan { + pub fn from_spans(mut vec: Vec) -> Self { vec.sort(); - MultiSpan { primary_spans: vec, span_labels: vec![] } + Self { primary_spans: vec, span_labels: vec![] } } pub fn push_span_label(&mut self, span: Span, label: String) { @@ -720,22 +784,23 @@ impl MultiSpan { /// span `P`, if there is at least one label with span `P`, we return /// those labels (marked as primary). But otherwise we return /// `SpanLabel` instances with empty labels. - pub fn span_labels(&self) -> Vec { - let is_primary = |span| self.primary_spans.contains(&span); + pub fn span_labels(&self) -> Vec> { + let is_primary = |span| self.primary_spans.contains(span); let mut span_labels = self .span_labels .iter() - .map(|&(span, ref label)| SpanLabel { - span, + .map(|(span, label)| Labelled { + span: span.clone(), is_primary: is_primary(span), label: Some(label.clone()), }) .collect::>(); - for &span in &self.primary_spans { - if !span_labels.iter().any(|sl| sl.span == span) { - span_labels.push(SpanLabel { span, is_primary: true, label: None }); + for span in &self.primary_spans { + if !span_labels.iter().any(|sl| &sl.span == span) { + let span = span.clone(); + span_labels.push(Labelled { span, is_primary: true, label: None }); } } @@ -748,15 +813,42 @@ impl MultiSpan { } } -impl From for MultiSpan { - fn from(span: Span) -> MultiSpan { - MultiSpan::from_span(span) +impl Multi { + pub fn map_span(self, f: impl Fn(S) -> S2) -> Multi { + Multi { + primary_spans: self.primary_spans.into_iter().map(&f).collect(), + span_labels: self.span_labels.into_iter().map(|(s, l)| (f(s), l.clone())).collect(), + } + } +} + +impl From for Multi { + fn from(span: Span) -> Multi { + Multi::from_span(span) + } +} + +impl From for MultiSpanId { + fn from(span: Span) -> MultiSpanId { + Multi::from_span(span) + } +} + +impl From for MultiSpanId { + fn from(ms: MultiSpan) -> MultiSpanId { + ms.map_span(SpanId::Span) + } +} + +impl From> for Multi { + fn from(spans: Vec) -> Multi { + Multi::from_spans(spans) } } -impl From> for MultiSpan { - fn from(spans: Vec) -> MultiSpan { - MultiSpan::from_spans(spans) +impl From> for MultiSpanId { + fn from(spans: Vec) -> MultiSpanId { + Multi::from_spans(spans).into() } } @@ -1555,7 +1647,7 @@ pub struct FileLines { pub lines: Vec, } -pub static SPAN_DEBUG: AtomicRef) -> fmt::Result> = +pub static SPAN_DEBUG: AtomicRef) -> fmt::Result> = AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _)); // _____________________________________________________________________________ diff --git a/src/librustc_target/abi/mod.rs b/src/librustc_target/abi/mod.rs index dcf181cb59f4a..10492419ef8b9 100644 --- a/src/librustc_target/abi/mod.rs +++ b/src/librustc_target/abi/mod.rs @@ -9,7 +9,7 @@ use std::ops::{Add, AddAssign, Deref, Mul, Range, RangeInclusive, Sub}; use rustc_index::vec::{Idx, IndexVec}; use rustc_macros::HashStable_Generic; -use rustc_span::Span; +use rustc_span::SpanId; pub mod call; @@ -971,7 +971,7 @@ pub trait LayoutOf { type TyAndLayout; fn layout_of(&self, ty: Self::Ty) -> Self::TyAndLayout; - fn spanned_layout_of(&self, ty: Self::Ty, _span: Span) -> Self::TyAndLayout { + fn spanned_layout_of(&self, ty: Self::Ty, _span: SpanId) -> Self::TyAndLayout { self.layout_of(ty) } } diff --git a/src/librustc_trait_selection/infer.rs b/src/librustc_trait_selection/infer.rs index 66df4fe951162..b5ed5a9a57f4d 100644 --- a/src/librustc_trait_selection/infer.rs +++ b/src/librustc_trait_selection/infer.rs @@ -44,7 +44,7 @@ impl<'cx, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'cx, 'tcx> { let ty = self.resolve_vars_if_possible(&ty); if !(param_env, ty).needs_infer() { - return ty.is_copy_modulo_regions(self.tcx, param_env, span); + return ty.is_copy_modulo_regions(self.tcx, param_env, span.into()); } let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem, None); diff --git a/src/librustc_trait_selection/opaque_types.rs b/src/librustc_trait_selection/opaque_types.rs index 4f8075b0171d3..09d9223bdfeec 100644 --- a/src/librustc_trait_selection/opaque_types.rs +++ b/src/librustc_trait_selection/opaque_types.rs @@ -407,7 +407,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { let opaque_type_generics = tcx.generics_of(def_id); - let span = tcx.def_span(def_id); + let span = tcx.real_def_span(def_id); // If there are required region bounds, we can use them. if opaque_defn.has_required_region_bounds { @@ -566,7 +566,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { return false; } - let span = self.tcx.def_span(opaque_type_def_id); + let span = self.tcx.real_def_span(opaque_type_def_id); // Without a feature-gate, we only generate member-constraints for async-await. let context_name = match opaque_defn.origin { @@ -836,7 +836,7 @@ impl TypeFolder<'tcx> for ReverseMapper<'tcx> { unexpected_hidden_region_diagnostic( self.tcx, None, - self.tcx.def_span(self.opaque_type_def_id), + self.tcx.real_def_span(self.opaque_type_def_id), hidden_ty, r, ) @@ -1121,7 +1121,7 @@ impl<'a, 'tcx> Instantiator<'a, 'tcx> { debug!("instantiate_opaque_types: returning concrete ty {:?}", opaque_defn.concrete_ty); return opaque_defn.concrete_ty; } - let span = tcx.def_span(def_id); + let span = tcx.real_def_span(def_id); debug!("fold_opaque_ty {:?} {:?}", self.value_span, span); let ty_var = infcx .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span }); diff --git a/src/librustc_trait_selection/traits/error_reporting/mod.rs b/src/librustc_trait_selection/traits/error_reporting/mod.rs index 405c656bad562..9a18d487f4993 100644 --- a/src/librustc_trait_selection/traits/error_reporting/mod.rs +++ b/src/librustc_trait_selection/traits/error_reporting/mod.rs @@ -381,7 +381,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { err.note(s.as_str()); } if let Some(ref s) = enclosing_scope { - let enclosing_scope_span = tcx.def_span( + let enclosing_scope_span = tcx.real_def_span( tcx.hir() .opt_local_def_id(obligation.cause.body_id) .unwrap_or_else(|| { @@ -1148,7 +1148,8 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { } let msg = format!("type mismatch resolving `{}`", predicate); - let error_id = (DiagnosticMessageId::ErrorId(271), Some(obligation.cause.span), msg); + let error_id = + (DiagnosticMessageId::ErrorId(271), Some(obligation.cause.span.into()), msg); let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id); if fresh { let mut diag = struct_span_err!( @@ -1294,8 +1295,8 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { Some(t) => Some(t), None => { let ty = parent_trait_ref.skip_binder().self_ty(); - let span = - TyCategory::from_ty(ty).map(|(_, def_id)| self.tcx.def_span(def_id)); + let span = TyCategory::from_ty(ty) + .map(|(_, def_id)| self.tcx.real_def_span(def_id)); Some((ty.to_string(), span)) } } @@ -1330,7 +1331,7 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { .collect(); for trait_with_same_path in traits_with_same_path { if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) { - let impl_span = self.tcx.def_span(impl_def_id); + let impl_span = self.tcx.real_def_span(impl_def_id); err.span_help(impl_span, "trait impl with same name found"); let trait_crate = self.tcx.crate_name(trait_with_same_path.krate); let crate_msg = format!( diff --git a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs index 5c4ba40bf38e3..03ab6edfb96f8 100644 --- a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs +++ b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs @@ -16,7 +16,7 @@ use rustc_middle::ty::{ TyCtxt, TypeFoldable, WithConstness, }; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{MultiSpan, Span, DUMMY_SP}; +use rustc_span::{MultiSpanId, Span, DUMMY_SP}; use std::fmt; use super::InferCtxtPrivExt; @@ -1448,7 +1448,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { )); let original_span = err.span.primary_span().unwrap(); - let mut span = MultiSpan::from_span(original_span); + let mut span = MultiSpanId::from_span(original_span); let message = outer_generator .and_then(|generator_did| { @@ -1483,10 +1483,10 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { if let Some(await_span) = from_awaited_ty { // The type causing this obligation is one being awaited at await_span. - let mut span = MultiSpan::from_span(await_span); + let mut span = MultiSpanId::from_span(await_span); span.push_span_label( - await_span, + await_span.into(), format!("await occurs here on type `{}`, which {}", target_ty, trait_explanation), ); @@ -1503,21 +1503,21 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { "note_obligation_cause_for_async_await generator_interior_types: {:#?}", tables.generator_interior_types ); - let mut span = MultiSpan::from_span(yield_span); + let mut span = MultiSpanId::from_span(yield_span); span.push_span_label( - yield_span, + yield_span.into(), format!("{} occurs here, with `{}` maybe used later", await_or_yield, snippet), ); span.push_span_label( - target_span, + target_span.into(), format!("has type `{}` which {}", target_ty, trait_explanation), ); // If available, use the scope span to annotate the drop location. if let Some(scope_span) = scope_span { span.push_span_label( - source_map.end_point(*scope_span), + source_map.end_point(*scope_span).into(), format!("`{}` is later dropped here", snippet), ); } diff --git a/src/librustc_trait_selection/traits/fulfill.rs b/src/librustc_trait_selection/traits/fulfill.rs index 1e056c96acd38..6927a1273f850 100644 --- a/src/librustc_trait_selection/traits/fulfill.rs +++ b/src/librustc_trait_selection/traits/fulfill.rs @@ -514,7 +514,7 @@ impl<'a, 'b, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'tcx> { def_id, substs, None, - Some(obligation.cause.span), + Some(obligation.cause.span.into()), ) { Ok(_) => ProcessResult::Changed(vec![]), Err(err) => ProcessResult::Error(CodeSelectionError(ConstEvalFailure(err))), diff --git a/src/librustc_trait_selection/traits/misc.rs b/src/librustc_trait_selection/traits/misc.rs index 7403b936391cc..bd5cece1ac46e 100644 --- a/src/librustc_trait_selection/traits/misc.rs +++ b/src/librustc_trait_selection/traits/misc.rs @@ -47,12 +47,12 @@ pub fn can_type_implement_copy( if ty.references_error() { continue; } - let span = tcx.def_span(field.did); + let span = tcx.real_def_span(field.did); let cause = ObligationCause { span, ..ObligationCause::dummy() }; let ctx = traits::FulfillmentContext::new(); match traits::fully_normalize(&infcx, ctx, cause, param_env, &ty) { Ok(ty) => { - if !infcx.type_is_copy_modulo_regions(param_env, ty, span) { + if !infcx.type_is_copy_modulo_regions(param_env, ty, span.into()) { infringing.push(field); } } diff --git a/src/librustc_trait_selection/traits/object_safety.rs b/src/librustc_trait_selection/traits/object_safety.rs index 96b2b904e6543..2448f3a0da441 100644 --- a/src/librustc_trait_selection/traits/object_safety.rs +++ b/src/librustc_trait_selection/traits/object_safety.rs @@ -20,7 +20,7 @@ use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, Subst} use rustc_middle::ty::{self, Predicate, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness}; use rustc_session::lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY; use rustc_span::symbol::Symbol; -use rustc_span::Span; +use rustc_span::SpanId; use smallvec::SmallVec; use std::iter; @@ -163,7 +163,7 @@ fn object_safety_violations_for_trait( tcx.associated_items(trait_def_id) .in_definition_order() .filter(|item| item.kind == ty::AssocKind::Const) - .map(|item| ObjectSafetyViolation::AssocConst(item.ident.name, item.ident.span)), + .map(|item| ObjectSafetyViolation::AssocConst(item.ident.name, item.ident.span.into())), ); debug!( @@ -177,7 +177,7 @@ fn object_safety_violations_for_trait( fn sized_trait_bound_spans<'tcx>( tcx: TyCtxt<'tcx>, bounds: hir::GenericBounds<'tcx>, -) -> impl 'tcx + Iterator { +) -> impl 'tcx + Iterator { bounds.iter().filter_map(move |b| match b { hir::GenericBound::Trait(trait_ref, hir::TraitBoundModifier::None) if trait_has_sized_self( @@ -186,13 +186,13 @@ fn sized_trait_bound_spans<'tcx>( ) => { // Fetch spans for supertraits that are `Sized`: `trait T: Super` - Some(trait_ref.span) + Some(trait_ref.span.into()) } _ => None, }) } -fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> { +fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[SpanId; 1]> { tcx.hir() .get_if_local(trait_def_id) .and_then(|node| match node { @@ -219,7 +219,7 @@ fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> .flatten() // Fetch spans for supertraits that are `Sized`: `trait T: Super`. .chain(sized_trait_bound_spans(tcx, bounds)) - .collect::>(), + .collect::>(), ), _ => None, }) @@ -230,7 +230,7 @@ fn predicates_reference_self( tcx: TyCtxt<'_>, trait_def_id: DefId, supertraits_only: bool, -) -> SmallVec<[Span; 1]> { +) -> SmallVec<[SpanId; 1]> { let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(tcx, trait_def_id)); let predicates = if supertraits_only { tcx.super_predicates_of(trait_def_id) @@ -322,7 +322,7 @@ fn object_safety_violation_for_method( tcx: TyCtxt<'_>, trait_def_id: DefId, method: &ty::AssocItem, -) -> Option<(MethodViolationCode, Span)> { +) -> Option<(MethodViolationCode, SpanId)> { debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method); // Any method that has a `Self : Sized` requisite is otherwise // exempt from the regulations. @@ -348,7 +348,7 @@ fn object_safety_violation_for_method( } _ => method.ident.span, }; - (v, span) + (v, span.into()) }) } @@ -367,8 +367,8 @@ fn virtual_call_violation_for_method<'tcx>( let sugg = tcx.hir().get_if_local(method.def_id).as_ref().and_then(|node| node.generics()).map( |generics| match generics.where_clause.predicates { - [] => (" where Self: Sized", generics.where_clause.span), - [.., pred] => (", Self: Sized", pred.span().shrink_to_hi()), + [] => (" where Self: Sized", generics.where_clause.span.into()), + [.., pred] => (", Self: Sized", pred.span().shrink_to_hi().into()), }, ); return Some(MethodViolationCode::StaticMethod(sugg)); diff --git a/src/librustc_trait_selection/traits/project.rs b/src/librustc_trait_selection/traits/project.rs index 47df82690e07d..c2eced0194378 100644 --- a/src/librustc_trait_selection/traits/project.rs +++ b/src/librustc_trait_selection/traits/project.rs @@ -423,7 +423,7 @@ pub fn normalize_projection_type<'a, 'b, 'tcx>( let def_id = projection_ty.item_def_id; let ty_var = selcx.infcx().next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::NormalizeProjectionType, - span: tcx.def_span(def_id), + span: tcx.real_def_span(def_id), }); let projection = ty::Binder::dummy(ty::ProjectionPredicate { projection_ty, ty: ty_var }); let obligation = @@ -756,7 +756,7 @@ fn normalize_to_error<'a, 'tcx>( let def_id = projection_ty.item_def_id; let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::NormalizeProjectionType, - span: tcx.def_span(def_id), + span: tcx.real_def_span(def_id), }); Normalized { value: new_value, obligations: vec![trait_obligation] } } diff --git a/src/librustc_trait_selection/traits/util.rs b/src/librustc_trait_selection/traits/util.rs index eff73cf4a2d8a..6e4375ee54ef2 100644 --- a/src/librustc_trait_selection/traits/util.rs +++ b/src/librustc_trait_selection/traits/util.rs @@ -1,5 +1,5 @@ use rustc_errors::DiagnosticBuilder; -use rustc_span::Span; +use rustc_span::SpanId; use smallvec::smallvec; use smallvec::SmallVec; @@ -31,11 +31,11 @@ pub struct TraitAliasExpander<'tcx> { /// Stores information about the expansion of a trait via a path of zero or more trait aliases. #[derive(Debug, Clone)] pub struct TraitAliasExpansionInfo<'tcx> { - pub path: SmallVec<[(ty::PolyTraitRef<'tcx>, Span); 4]>, + pub path: SmallVec<[(ty::PolyTraitRef<'tcx>, SpanId); 4]>, } impl<'tcx> TraitAliasExpansionInfo<'tcx> { - fn new(trait_ref: ty::PolyTraitRef<'tcx>, span: Span) -> Self { + fn new(trait_ref: ty::PolyTraitRef<'tcx>, span: SpanId) -> Self { Self { path: smallvec![(trait_ref, span)] } } @@ -63,15 +63,15 @@ impl<'tcx> TraitAliasExpansionInfo<'tcx> { &self.top().0 } - pub fn top(&self) -> &(ty::PolyTraitRef<'tcx>, Span) { + pub fn top(&self) -> &(ty::PolyTraitRef<'tcx>, SpanId) { self.path.last().unwrap() } - pub fn bottom(&self) -> &(ty::PolyTraitRef<'tcx>, Span) { + pub fn bottom(&self) -> &(ty::PolyTraitRef<'tcx>, SpanId) { self.path.first().unwrap() } - fn clone_and_push(&self, trait_ref: ty::PolyTraitRef<'tcx>, span: Span) -> Self { + fn clone_and_push(&self, trait_ref: ty::PolyTraitRef<'tcx>, span: SpanId) -> Self { let mut path = self.path.clone(); path.push((trait_ref, span)); @@ -81,7 +81,7 @@ impl<'tcx> TraitAliasExpansionInfo<'tcx> { pub fn expand_trait_aliases<'tcx>( tcx: TyCtxt<'tcx>, - trait_refs: impl Iterator, Span)>, + trait_refs: impl Iterator, SpanId)>, ) -> TraitAliasExpander<'tcx> { let items: Vec<_> = trait_refs.map(|(trait_ref, span)| TraitAliasExpansionInfo::new(trait_ref, span)).collect(); diff --git a/src/librustc_trait_selection/traits/wf.rs b/src/librustc_trait_selection/traits/wf.rs index 1d4afeaae42c4..98e987c152d9f 100644 --- a/src/librustc_trait_selection/traits/wf.rs +++ b/src/librustc_trait_selection/traits/wf.rs @@ -549,7 +549,8 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { .into_iter() .zip(predicates.spans.into_iter()) .map(|(pred, span)| { - let cause = self.cause(traits::BindingObligation(def_id, span)); + let cause = + self.cause(traits::BindingObligation(def_id, self.infcx.tcx.reify_span(span))); traits::Obligation::new(cause, self.param_env, pred) }) .filter(|pred| !pred.has_escaping_bound_vars()) diff --git a/src/librustc_traits/dropck_outlives.rs b/src/librustc_traits/dropck_outlives.rs index 76ff58d61a257..06b3f612c5adf 100644 --- a/src/librustc_traits/dropck_outlives.rs +++ b/src/librustc_traits/dropck_outlives.rs @@ -289,7 +289,7 @@ crate fn adt_dtorck_constraint( def_id: DefId, ) -> Result, NoSolution> { let def = tcx.adt_def(def_id); - let span = tcx.def_span(def_id); + let span = tcx.real_def_span(def_id); debug!("dtorck_constraint: {:?}", def); if def.is_phantom_data() { diff --git a/src/librustc_ty/needs_drop.rs b/src/librustc_ty/needs_drop.rs index 97994b465b54c..54de31c96f98e 100644 --- a/src/librustc_ty/needs_drop.rs +++ b/src/librustc_ty/needs_drop.rs @@ -5,7 +5,7 @@ use rustc_hir::def_id::DefId; use rustc_middle::ty::subst::Subst; use rustc_middle::ty::util::{needs_drop_components, AlwaysRequiresDrop}; use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_span::DUMMY_SP; +use rustc_span::DUMMY_SPID; type NeedsDropResult = Result; @@ -71,7 +71,7 @@ where // Not having a `Span` isn't great. But there's hopefully some other // recursion limit error as well. tcx.sess.span_err( - DUMMY_SP, + DUMMY_SPID, &format!("overflow while checking whether `{}` requires drop", self.query_ty), ); return Some(Err(AlwaysRequiresDrop)); @@ -91,7 +91,7 @@ where for component in components { match component.kind { - _ if component.is_copy_modulo_regions(tcx, self.param_env, DUMMY_SP) => (), + _ if component.is_copy_modulo_regions(tcx, self.param_env, DUMMY_SPID) => (), ty::Closure(_, substs) => { for upvar_ty in substs.as_closure().upvar_tys() { diff --git a/src/librustc_ty/ty.rs b/src/librustc_ty/ty.rs index 6add099e75bd6..c3cb8d75f8372 100644 --- a/src/librustc_ty/ty.rs +++ b/src/librustc_ty/ty.rs @@ -225,7 +225,7 @@ fn associated_items(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssociatedItems<'_> { ty::AssociatedItems::new(items) } -fn def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span { +fn real_def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span { tcx.hir().span_if_local(def_id).unwrap() } @@ -274,7 +274,7 @@ fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> { .map_or(hir::CRATE_HIR_ID, |id| { tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id) }); - let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id); + let cause = traits::ObligationCause::misc(tcx.real_def_span(def_id), body_id); traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause) } @@ -376,7 +376,7 @@ pub fn provide(providers: &mut ty::query::Providers<'_>) { associated_item_def_ids, associated_items, adt_sized_constraint, - def_span, + real_def_span, param_env, trait_of_item, crate_disambiguator, diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 6529d784ad452..6eadaba1ebcdb 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -27,7 +27,7 @@ use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, LATE_BOUND_LIFETI 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_span::{MultiSpan, Span, SpanId, DUMMY_SP}; use rustc_target::spec::abi; use rustc_trait_selection::traits; use rustc_trait_selection::traits::astconv_object_safety_violations; @@ -1006,7 +1006,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { pub(super) fn instantiate_poly_trait_ref_inner( &self, trait_ref: &hir::TraitRef<'_>, - span: Span, + span: SpanId, constness: Constness, self_ty: Ty<'tcx>, bounds: &mut Bounds<'tcx>, @@ -1079,7 +1079,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ) -> Result<(), GenericArgCountMismatch> { self.instantiate_poly_trait_ref_inner( &poly_trait_ref.trait_ref, - poly_trait_ref.span, + poly_trait_ref.span.into(), constness, self_ty, bounds, @@ -1280,7 +1280,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } bounds.region_bounds.extend( - region_bounds.into_iter().map(|r| (self.ast_region_to_region(r, None), r.span)), + region_bounds.into_iter().map(|r| (self.ast_region_to_region(r, None), r.span.into())), ); } @@ -1313,7 +1313,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { bounds.trait_bounds.sort_by_key(|(t, _, _)| t.def_id()); bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default { - if !self.is_unsized(ast_bounds, span) { Some(span) } else { None } + if !self.is_unsized(ast_bounds, span) { Some(span.into()) } else { None } } else { None }; @@ -1476,7 +1476,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ), ty, }), - binding.span, + binding.span.into(), )); } ConvertedBindingKind::Constraint(ast_bounds) => { @@ -1529,8 +1529,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // Expand trait aliases recursively and check that only one regular (non-auto) trait // is used and no 'maybe' bounds are used. - let expanded_traits = - traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b))); + let expanded_traits = traits::expand_trait_aliases( + tcx, + bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b.into())), + ); let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) = expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id())); if regular_traits.len() > 1 { @@ -1598,6 +1600,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ); match obligation.predicate { ty::Predicate::Trait(pred, _) => { + let span = tcx.reify_span(span); associated_types.entry(span).or_default().extend( tcx.associated_items(pred.def_id()) .in_definition_order() @@ -3007,22 +3010,22 @@ pub struct Bounds<'tcx> { /// A list of region bounds on the (implicit) self type. So if you /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but /// the `T` is not explicitly included). - pub region_bounds: Vec<(ty::Region<'tcx>, Span)>, + pub region_bounds: Vec<(ty::Region<'tcx>, SpanId)>, /// A list of trait bounds. So if you had `T: Debug` this would be /// `T: Debug`. Note that the self-type is explicit here. - pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span, Constness)>, + pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, SpanId, Constness)>, /// A list of projection equality bounds. So if you had `T: /// Iterator` this would include `::Item => u32`. Note that the self-type is explicit /// here. - pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>, + pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, SpanId)>, /// `Some` if there is *no* `?Sized` predicate. The `span` /// is the location in the source of the `T` declaration which can /// be cited as the source of the `T: Sized` requirement. - pub implicitly_sized: Option, + pub implicitly_sized: Option, } impl<'tcx> Bounds<'tcx> { @@ -3034,7 +3037,7 @@ impl<'tcx> Bounds<'tcx> { &self, tcx: TyCtxt<'tcx>, param_ty: Ty<'tcx>, - ) -> Vec<(ty::Predicate<'tcx>, Span)> { + ) -> Vec<(ty::Predicate<'tcx>, SpanId)> { // If it could be sized, and is, add the `Sized` predicate. let sized_predicate = self.implicitly_sized.and_then(|span| { tcx.lang_items().sized_trait().map(|sized| { diff --git a/src/librustc_typeck/check/autoderef.rs b/src/librustc_typeck/check/autoderef.rs index ae6c1738da77d..27db08ee098cb 100644 --- a/src/librustc_typeck/check/autoderef.rs +++ b/src/librustc_typeck/check/autoderef.rs @@ -238,7 +238,7 @@ pub fn report_autoderef_recursion_limit_error<'tcx>(tcx: TyCtxt<'tcx>, span: Spa // We've reached the recursion limit, error gracefully. let suggested_limit = *tcx.sess.recursion_limit.get() * 2; let msg = format!("reached the recursion limit while auto-dereferencing `{:?}`", ty); - let error_id = (DiagnosticMessageId::ErrorId(55), Some(span), msg); + let error_id = (DiagnosticMessageId::ErrorId(55), Some(span.into()), msg); let fresh = tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id); if fresh { struct_span_err!( diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs index 29cd9681295be..3676b526d6368 100644 --- a/src/librustc_typeck/check/compare_method.rs +++ b/src/librustc_typeck/check/compare_method.rs @@ -811,7 +811,7 @@ fn compare_synthetic_generics<'tcx>( if impl_synthetic != trait_synthetic { let impl_hir_id = tcx.hir().as_local_hir_id(impl_def_id.expect_local()); let impl_span = tcx.hir().span(impl_hir_id); - let trait_span = tcx.def_span(trait_def_id); + let trait_span = tcx.real_def_span(trait_def_id); let mut err = struct_span_err!( tcx.sess, impl_span, diff --git a/src/librustc_typeck/check/dropck.rs b/src/librustc_typeck/check/dropck.rs index 478a848cf09dd..1d66ec017b95f 100644 --- a/src/librustc_typeck/check/dropck.rs +++ b/src/librustc_typeck/check/dropck.rs @@ -82,7 +82,7 @@ fn ensure_drop_params_and_item_params_correspond<'tcx>( let named_type = tcx.type_of(self_type_did); - let drop_impl_span = tcx.def_span(drop_impl_did); + let drop_impl_span = tcx.real_def_span(drop_impl_did); let fresh_impl_substs = infcx.fresh_substs_for_item(drop_impl_span, drop_impl_did.to_def_id()); let fresh_impl_self_ty = drop_impl_ty.subst(tcx, fresh_impl_substs); diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index 64dc34ab3b0a7..4c7271db8836d 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -11,7 +11,7 @@ use rustc_middle::ty::adjustment::{AllowTwoPhase, AutoBorrow, AutoBorrowMutabili use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::subst::{Subst, SubstsRef}; use rustc_middle::ty::{self, GenericParamDefKind, Ty}; -use rustc_span::Span; +use rustc_span::{Span, SpanId}; use rustc_trait_selection::traits; use std::ops::Deref; @@ -32,7 +32,7 @@ impl<'a, 'tcx> Deref for ConfirmContext<'a, 'tcx> { pub struct ConfirmResult<'tcx> { pub callee: MethodCallee<'tcx>, - pub illegal_sized_bound: Option, + pub illegal_sized_bound: Option, } impl<'a, 'tcx> FnCtxt<'a, 'tcx> { @@ -565,7 +565,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { fn predicates_require_illegal_sized_bound( &self, predicates: &ty::InstantiatedPredicates<'tcx>, - ) -> Option { + ) -> Option { let sized_def_id = match self.tcx.lang_items().sized_trait() { Some(def_id) => def_id, None => return None, @@ -581,7 +581,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { .find_map( |(p, span)| if *p == obligation.predicate { Some(*span) } else { None }, ) - .unwrap_or(rustc_span::DUMMY_SP); + .unwrap_or(rustc_span::DUMMY_SPID); Some((trait_pred, span)) } _ => None, diff --git a/src/librustc_typeck/check/method/mod.rs b/src/librustc_typeck/check/method/mod.rs index a254aecf07bab..38f3edb25a24d 100644 --- a/src/librustc_typeck/check/method/mod.rs +++ b/src/librustc_typeck/check/method/mod.rs @@ -207,6 +207,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.confirm_method(span, self_expr, call_expr, self_ty, pick.clone(), segment); if let Some(span) = result.illegal_sized_bound { + let span = self.tcx.reify_span(span); let mut needs_mut = false; if let ty::Ref(region, t_type, mutability) = self_ty.kind { let trait_type = self diff --git a/src/librustc_typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs index 7f1d77e5b97d8..249de8b62bc00 100644 --- a/src/librustc_typeck/check/method/probe.rs +++ b/src/librustc_typeck/check/method/probe.rs @@ -1634,11 +1634,11 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { GenericParamDefKind::Type { .. } => self .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::SubstitutionPlaceholder, - span: self.tcx.def_span(def_id), + span: self.tcx.real_def_span(def_id), }) .into(), GenericParamDefKind::Const { .. } => { - let span = self.tcx.def_span(def_id); + let span = self.tcx.real_def_span(def_id); let origin = ConstVariableOrigin { kind: ConstVariableOriginKind::SubstitutionPlaceholder, span, diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs index cf26c94418e2d..df6873d31f0ec 100644 --- a/src/librustc_typeck/check/method/suggest.rs +++ b/src/librustc_typeck/check/method/suggest.rs @@ -195,7 +195,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .tcx .sess .source_map() - .guess_head_span(self.tcx.def_span(item.def_id)); + .guess_head_span(self.tcx.real_def_span(item.def_id)); let idx = if sources.len() > 1 { let msg = &format!( "candidate #{} is defined in the trait `{}`", @@ -568,7 +568,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut restrict_type_params = false; if !unsatisfied_predicates.is_empty() { let def_span = |def_id| { - self.tcx.sess.source_map().guess_head_span(self.tcx.def_span(def_id)) + self.tcx.sess.source_map().guess_head_span(self.tcx.real_def_span(def_id)) }; let mut type_params = FxHashMap::default(); let mut bound_spans = vec![]; diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 956e09ec52b4a..810f56119272f 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -132,7 +132,7 @@ use rustc_session::Session; use rustc_span::hygiene::DesugaringKind; use rustc_span::source_map::{original_sp, DUMMY_SP}; use rustc_span::symbol::{kw, sym, Ident}; -use rustc_span::{self, BytePos, MultiSpan, Span}; +use rustc_span::{self, BytePos, MultiSpan, Span, SpanId}; use rustc_target::abi::VariantIdx; use rustc_target::spec::abi::Abi; use rustc_trait_selection::infer::InferCtxtExt as _; @@ -3222,9 +3222,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { span: Span, def_id: DefId, substs: SubstsRef<'tcx>, - ) -> (ty::InstantiatedPredicates<'tcx>, Vec) { + ) -> (ty::InstantiatedPredicates<'tcx>, Vec) { let bounds = self.tcx.predicates_of(def_id); - let spans: Vec = bounds.predicates.iter().map(|(_, span)| *span).collect(); + let spans: Vec<_> = bounds.predicates.iter().map(|(_, span)| *span).collect(); let result = bounds.instantiate(self.tcx, substs); let result = self.normalize_associated_types_in(span, &result); debug!( @@ -3369,7 +3369,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // self.out.extend(obligations); let cause = traits::ObligationCause::new( - self.tcx.def_span(const_def_id.to_def_id()), + self.tcx.real_def_span(const_def_id.to_def_id()), self.body_id, traits::MiscObligation, ); @@ -5682,7 +5682,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { // This makes the error point at the bound, but we want to point at the argument if let Some(span) = spans.get(i) { - obligation.cause.code = traits::BindingObligation(def_id, *span); + let span = self.tcx.reify_span(*span); + obligation.cause.code = traits::BindingObligation(def_id, span); } self.register_predicate(obligation); } diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index b79ac50da8fa3..e72e409132467 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -241,7 +241,8 @@ fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem if tcx.object_safety_violations(trait_def_id).is_empty() { return; } - let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect(); + let sugg: Vec<_> = + trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect(); tcx.sess .struct_span_err( trait_should_be_self, @@ -418,7 +419,7 @@ fn check_type_defn<'tcx, F>( InternalSubsts::identity_for_item(fcx.tcx, discr_def_id.to_def_id()); let cause = traits::ObligationCause::new( - fcx.tcx.def_span(discr_def_id), + fcx.tcx.real_def_span(discr_def_id), fcx.body_id, traits::MiscObligation, ); @@ -545,6 +546,7 @@ fn check_associated_type_defaults(fcx: &FnCtxt<'_, '_>, trait_def_id: DefId) { let mut norm = DefaultNormalizer { tcx, map }; let predicates = fcx.tcx.predicates_of(trait_def_id); for &(orig_pred, span) in predicates.predicates.iter() { + let span = tcx.reify_span(span); let pred = orig_pred.fold_with(&mut norm); if pred != orig_pred { // Mentions one of the defaulted assoc. types @@ -698,7 +700,7 @@ fn check_where_clauses<'tcx, 'fcx>( if !ty.needs_subst() { fcx.register_wf_obligation( ty, - fcx.tcx.def_span(param.def_id), + fcx.tcx.real_def_span(param.def_id), ObligationCauseCode::MiscObligation, ); } @@ -797,6 +799,7 @@ fn check_where_clauses<'tcx, 'fcx>( // Note the subtle difference from how we handle `predicates` // below: there, we are not trying to prove those predicates // to be *true* but merely *well-formed*. + let sp = tcx.reify_span(sp); let pred = fcx.normalize_associated_types_in(sp, &pred); let cause = traits::ObligationCause::new(sp, fcx.body_id, traits::ItemObligation(def_id)); @@ -808,7 +811,7 @@ fn check_where_clauses<'tcx, 'fcx>( if let Some((return_ty, span)) = return_ty { let opaque_types = check_opaque_types(tcx, fcx, def_id.expect_local(), span, return_ty); for _ in 0..opaque_types.len() { - predicates.spans.push(span); + predicates.spans.push(span.into()); } predicates.predicates.extend(opaque_types); } @@ -819,7 +822,13 @@ fn check_where_clauses<'tcx, 'fcx>( assert_eq!(predicates.predicates.len(), predicates.spans.len()); let wf_obligations = predicates.predicates.iter().zip(predicates.spans.iter()).flat_map(|(p, sp)| { - traits::wf::predicate_obligations(fcx, fcx.param_env, fcx.body_id, p, *sp) + traits::wf::predicate_obligations( + fcx, + fcx.param_env, + fcx.body_id, + p, + tcx.reify_span(*sp), + ) }); for obligation in wf_obligations.chain(default_obligations) { diff --git a/src/librustc_typeck/check/writeback.rs b/src/librustc_typeck/check/writeback.rs index c5bf151bc1e11..fc9a816eb91d4 100644 --- a/src/librustc_typeck/check/writeback.rs +++ b/src/librustc_typeck/check/writeback.rs @@ -403,7 +403,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { if !errors_buffer.is_empty() { errors_buffer.sort_by_key(|diag| diag.span.primary_span()); for diag in errors_buffer.drain(..) { - self.tcx().sess.diagnostic().emit_diagnostic(&diag); + self.tcx().sess.diagnostic().emit_diagnostic(diag); } } } diff --git a/src/librustc_typeck/check_unused.rs b/src/librustc_typeck/check_unused.rs index dfe86aecbf727..5628453b506f8 100644 --- a/src/librustc_typeck/check_unused.rs +++ b/src/librustc_typeck/check_unused.rs @@ -5,7 +5,7 @@ use rustc_hir::def_id::{DefId, DefIdSet, LOCAL_CRATE}; use rustc_hir::itemlikevisit::ItemLikeVisitor; use rustc_middle::ty::TyCtxt; use rustc_session::lint; -use rustc_span::{Span, Symbol}; +use rustc_span::{Span, SpanId, Symbol}; pub fn check_crate(tcx: TyCtxt<'_>) { let mut used_trait_imports = DefIdSet::default(); @@ -70,7 +70,7 @@ fn unused_crates_lint(tcx: TyCtxt<'_>) { // Collect first the crates that are completely unused. These we // can always suggest removing (no matter which edition we are // in). - let unused_extern_crates: FxHashMap = tcx + let unused_extern_crates: FxHashMap = tcx .maybe_unused_extern_crates(LOCAL_CRATE) .iter() .filter(|&&(def_id, _)| { @@ -125,7 +125,7 @@ fn unused_crates_lint(tcx: TyCtxt<'_>) { .get_attrs(extern_crate.def_id) .iter() .map(|attr| attr.span) - .fold(span, |acc, attr_span| acc.to(attr_span)); + .fold(tcx.reify_span(span), |acc, attr_span| acc.to(attr_span)); lint.build("unused extern crate") .span_suggestion_short( diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 854bd03b26486..92698dbf3916e 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -43,7 +43,7 @@ use rustc_middle::ty::{ReprOptions, ToPredicate, WithConstness}; use rustc_session::lint; use rustc_session::parse::feature_err; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{Span, SpanId, DUMMY_SP}; use rustc_target::spec::abi; use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName; @@ -527,8 +527,10 @@ 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); - extend = - Some((identity_trait_ref.without_const().to_predicate(), item.span)); + extend = Some(( + identity_trait_ref.without_const().to_predicate(), + item.span.into(), + )); } generics } @@ -551,7 +553,8 @@ fn type_param_predicates( .filter(|(predicate, _)| match predicate { ty::Predicate::Trait(ref data, _) => data.skip_binder().self_ty().is_param(index), _ => false, - }), + }) + .map(|(p, s)| (p, s.into())), ); result.predicates = tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates)); @@ -569,7 +572,7 @@ impl ItemCtxt<'tcx> { param_id: hir::HirId, ty: Ty<'tcx>, only_self_bounds: OnlySelfBounds, - ) -> Vec<(ty::Predicate<'tcx>, Span)> { + ) -> Vec<(ty::Predicate<'tcx>, SpanId)> { let constness = self.default_constness_for_trait_bounds(); let from_ty_params = ast_generics .params @@ -1651,11 +1654,11 @@ fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> { // prove that the trait applies to the types that were // used, and adding the predicate into this list ensures // that this is done. - let span = tcx.sess.source_map().guess_head_span(tcx.def_span(def_id)); + let span = tcx.sess.source_map().guess_head_span(tcx.real_def_span(def_id)); result.predicates = tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once(( ty::TraitRef::identity(tcx, def_id).without_const().to_predicate(), - span, + span.into(), )))); } debug!("predicates_of(def_id={:?}) = {:?}", def_id, result); @@ -1674,8 +1677,8 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat /// compile-fail UI tests. // FIXME(eddyb) just use `IndexSet` from `indexmap`. struct UniquePredicates<'tcx> { - predicates: Vec<(ty::Predicate<'tcx>, Span)>, - uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>, + predicates: Vec<(ty::Predicate<'tcx>, SpanId)>, + uniques: FxHashSet<(ty::Predicate<'tcx>, SpanId)>, } impl<'tcx> UniquePredicates<'tcx> { @@ -1683,13 +1686,13 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat UniquePredicates { predicates: vec![], uniques: FxHashSet::default() } } - fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) { + fn push(&mut self, value: (ty::Predicate<'tcx>, SpanId)) { if self.uniques.insert(value) { self.predicates.push(value); } } - fn extend, Span)>>(&mut self, iter: I) { + fn extend, SpanId)>>(&mut self, iter: I) { for value in iter { self.push(value); } @@ -1728,7 +1731,7 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat opaque_ty, bounds, SizedByDefault::Yes, - tcx.def_span(def_id), + tcx.real_def_span(def_id), ); predicates.extend(bounds.predicates(tcx, opaque_ty)); @@ -1776,7 +1779,7 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat opaque_ty, bounds, SizedByDefault::Yes, - tcx.def_span(def_id), + tcx.real_def_span(def_id), ); bounds.predicates(tcx, opaque_ty) @@ -1852,7 +1855,7 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat hir::GenericBound::Outlives(lt) => { let bound = AstConv::ast_region_to_region(&icx, <, None); let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound)); - predicates.push((outlives.to_predicate(), lt.span)); + predicates.push((outlives.to_predicate(), lt.span.into())); } _ => bug!(), }); @@ -1894,7 +1897,7 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat // users who never wrote `where Type:,` themselves, to // compiler/tooling bugs from not handling WF predicates. } else { - let span = bound_pred.bounded_ty.span; + let span = bound_pred.bounded_ty.span.into(); let re_root_empty = tcx.lifetimes.re_root_empty; let predicate = ty::OutlivesPredicate(ty, re_root_empty); predicates.push(( @@ -1927,7 +1930,8 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat &hir::GenericBound::Outlives(ref lifetime) => { let region = AstConv::ast_region_to_region(&icx, lifetime, None); let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region)); - predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span)) + predicates + .push((ty::Predicate::TypeOutlives(pred), lifetime.span.into())) } } } @@ -1944,7 +1948,7 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat }; let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2)); - (ty::Predicate::RegionOutlives(pred), span) + (ty::Predicate::RegionOutlives(pred), span.into()) })) } @@ -1992,7 +1996,7 @@ fn associated_item_predicates( def_id: DefId, self_trait_ref: ty::TraitRef<'tcx>, trait_item_ref: &hir::TraitItemRef, -) -> Vec<(ty::Predicate<'tcx>, Span)> { +) -> Vec<(ty::Predicate<'tcx>, SpanId)> { let trait_item = tcx.hir().trait_item(trait_item_ref.id); let item_def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id); let bounds = match trait_item.kind { @@ -2099,7 +2103,7 @@ fn predicates_from_bound<'tcx>( param_ty: Ty<'tcx>, bound: &'tcx hir::GenericBound<'tcx>, constness: hir::Constness, -) -> Vec<(ty::Predicate<'tcx>, Span)> { +) -> Vec<(ty::Predicate<'tcx>, SpanId)> { match *bound { hir::GenericBound::Trait(ref tr, modifier) => { let constness = match modifier { @@ -2115,7 +2119,7 @@ fn predicates_from_bound<'tcx>( hir::GenericBound::Outlives(ref lifetime) => { let region = astconv.ast_region_to_region(lifetime, None); let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region)); - vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)] + vec![(ty::Predicate::TypeOutlives(pred), lifetime.span.into())] } } } diff --git a/src/librustc_typeck/collect/type_of.rs b/src/librustc_typeck/collect/type_of.rs index cf0e3f9cdf592..7e6964a33056b 100644 --- a/src/librustc_typeck/collect/type_of.rs +++ b/src/librustc_typeck/collect/type_of.rs @@ -444,7 +444,7 @@ fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> { ); // FIXME(oli-obk): trace the actual span from inference to improve errors. - let span = self.tcx.def_span(def_id); + let span = self.tcx.real_def_span(def_id); // HACK(eddyb) this check shouldn't be needed, as `wfcheck` // performs the same checks, in theory, but I've kept it here diff --git a/src/librustc_typeck/constrained_generic_params.rs b/src/librustc_typeck/constrained_generic_params.rs index 07ff3bc85cc19..91b14fe781d44 100644 --- a/src/librustc_typeck/constrained_generic_params.rs +++ b/src/librustc_typeck/constrained_generic_params.rs @@ -1,7 +1,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_middle::ty::fold::{TypeFoldable, TypeVisitor}; use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_span::source_map::Span; +use rustc_span::SpanId; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct Parameter(pub u32); @@ -146,7 +146,7 @@ pub fn identify_constrained_generic_params<'tcx>( /// think of any. pub fn setup_constraining_predicates<'tcx>( tcx: TyCtxt<'tcx>, - predicates: &mut [(ty::Predicate<'tcx>, Span)], + predicates: &mut [(ty::Predicate<'tcx>, SpanId)], impl_trait_ref: Option>, input_parameters: &mut FxHashSet, ) { diff --git a/src/librustc_typeck/impl_wf_check.rs b/src/librustc_typeck/impl_wf_check.rs index e13d9ea2b2626..3fa1f1a18b296 100644 --- a/src/librustc_typeck/impl_wf_check.rs +++ b/src/librustc_typeck/impl_wf_check.rs @@ -160,7 +160,7 @@ fn enforce_impl_params_are_constrained( if !input_parameters.contains(&cgp::Parameter::from(param_ty)) { report_unused_parameter( tcx, - tcx.def_span(param.def_id), + tcx.real_def_span(param.def_id), "type", ¶m_ty.to_string(), ); @@ -173,7 +173,7 @@ fn enforce_impl_params_are_constrained( { report_unused_parameter( tcx, - tcx.def_span(param.def_id), + tcx.real_def_span(param.def_id), "lifetime", ¶m.name.to_string(), ); @@ -184,7 +184,7 @@ fn enforce_impl_params_are_constrained( if !input_parameters.contains(&cgp::Parameter::from(param_ct)) { report_unused_parameter( tcx, - tcx.def_span(param.def_id), + tcx.real_def_span(param.def_id), "const", ¶m_ct.to_string(), ); diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index 8d8a1b4d96761..5e4e536871b72 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -100,7 +100,7 @@ use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::util; use rustc_session::config::EntryFnType; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{Span, DUMMY_SPID}; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _; use rustc_trait_selection::traits::{ @@ -154,7 +154,7 @@ fn require_same_types<'tcx>( fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: LocalDefId) { let main_id = tcx.hir().as_local_hir_id(main_def_id); - let main_span = tcx.def_span(main_def_id); + let main_span = tcx.real_def_span(main_def_id); let main_t = tcx.type_of(main_def_id); match main_t.kind { ty::FnDef(..) => { @@ -233,7 +233,7 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: LocalDefId) { fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: LocalDefId) { let start_id = tcx.hir().as_local_hir_id(start_def_id); - let start_span = tcx.def_span(start_def_id); + let start_span = tcx.real_def_span(start_def_id); let start_t = tcx.type_of(start_def_id); match start_t.kind { ty::FnDef(..) => { @@ -398,7 +398,7 @@ pub fn hir_trait_to_predicates<'tcx>( let _ = AstConv::instantiate_poly_trait_ref_inner( &item_cx, hir_trait, - DUMMY_SP, + DUMMY_SPID, hir::Constness::NotConst, self_ty, &mut bounds, diff --git a/src/librustc_typeck/outlives/implicit_infer.rs b/src/librustc_typeck/outlives/implicit_infer.rs index 15c72f8704f65..e9f9d814300e7 100644 --- a/src/librustc_typeck/outlives/implicit_infer.rs +++ b/src/librustc_typeck/outlives/implicit_infer.rs @@ -5,7 +5,7 @@ use rustc_hir::itemlikevisit::ItemLikeVisitor; use rustc_hir::Node; use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst}; use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_span::Span; +use rustc_span::SpanId; use super::explicit::ExplicitPredicatesMap; use super::utils::*; @@ -114,7 +114,7 @@ impl<'cx, 'tcx> ItemLikeVisitor<'tcx> for InferVisitor<'cx, 'tcx> { fn insert_required_predicates_to_be_wf<'tcx>( tcx: TyCtxt<'tcx>, field_ty: Ty<'tcx>, - field_span: Span, + field_span: SpanId, global_inferred_outlives: &FxHashMap>, required_predicates: &mut RequiredPredicates<'tcx>, explicit_map: &mut ExplicitPredicatesMap<'tcx>, diff --git a/src/librustc_typeck/outlives/mod.rs b/src/librustc_typeck/outlives/mod.rs index a49d8e5ed0f0a..93e1bfe44bfec 100644 --- a/src/librustc_typeck/outlives/mod.rs +++ b/src/librustc_typeck/outlives/mod.rs @@ -5,7 +5,7 @@ use rustc_middle::ty::query::Providers; use rustc_middle::ty::subst::GenericArgKind; use rustc_middle::ty::{self, CratePredicatesMap, TyCtxt}; use rustc_span::symbol::sym; -use rustc_span::Span; +use rustc_span::SpanId; mod explicit; mod implicit_infer; @@ -17,7 +17,7 @@ pub fn provide(providers: &mut Providers<'_>) { *providers = Providers { inferred_outlives_of, inferred_outlives_crate, ..*providers }; } -fn inferred_outlives_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[(ty::Predicate<'_>, Span)] { +fn inferred_outlives_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[(ty::Predicate<'_>, SpanId)] { let id = tcx.hir().as_local_hir_id(item_def_id.expect_local()); match tcx.hir().get(id) { @@ -87,13 +87,13 @@ fn inferred_outlives_crate(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CratePredica ty::Predicate::TypeOutlives(ty::Binder::bind(ty::OutlivesPredicate( ty1, region2, ))), - span, + span.into(), )), GenericArgKind::Lifetime(region1) => Some(( ty::Predicate::RegionOutlives(ty::Binder::bind(ty::OutlivesPredicate( region1, region2, ))), - span, + span.into(), )), GenericArgKind::Const(_) => { // Generic consts don't impose any constraints. diff --git a/src/librustc_typeck/outlives/utils.rs b/src/librustc_typeck/outlives/utils.rs index 3bbe3e34a6a45..c5507367b05fa 100644 --- a/src/librustc_typeck/outlives/utils.rs +++ b/src/librustc_typeck/outlives/utils.rs @@ -1,14 +1,14 @@ use rustc_middle::ty::outlives::Component; use rustc_middle::ty::subst::{GenericArg, GenericArgKind}; use rustc_middle::ty::{self, Region, RegionKind, Ty, TyCtxt}; -use rustc_span::Span; +use rustc_span::SpanId; use smallvec::smallvec; use std::collections::BTreeMap; /// Tracks the `T: 'a` or `'a: 'a` predicates that we have inferred /// must be added to the struct header. pub type RequiredPredicates<'tcx> = - BTreeMap, ty::Region<'tcx>>, Span>; + BTreeMap, ty::Region<'tcx>>, SpanId>; /// Given a requirement `T: 'a` or `'b: 'a`, deduce the /// outlives_component and add it to `required_predicates` @@ -16,7 +16,7 @@ pub fn insert_outlives_predicate<'tcx>( tcx: TyCtxt<'tcx>, kind: GenericArg<'tcx>, outlived_region: Region<'tcx>, - span: Span, + span: SpanId, required_predicates: &mut RequiredPredicates<'tcx>, ) { // If the `'a` region is bound within the field type itself, we diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 8cd9ab41aa40a..c18ae798f298b 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -87,7 +87,7 @@ impl, U> Clean> for Option { impl Clean for CrateNum { fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate { let root = DefId { krate: *self, index: CRATE_DEF_INDEX }; - let krate_span = cx.tcx.def_span(root); + let krate_span = cx.tcx.real_def_span(root); let krate_src = cx.sess().source_map().span_to_filename(krate_span); // Collect all inner modules which are tagged as implementations of @@ -1325,7 +1325,7 @@ impl Clean for ty::AssocItem { deprecation: get_deprecation(cx, self.def_id), def_id: self.def_id, attrs: inline::load_attrs(cx, self.def_id).clean(cx), - source: cx.tcx.def_span(self.def_id).clean(cx), + source: cx.tcx.real_def_span(self.def_id).clean(cx), inner, } } @@ -1352,7 +1352,7 @@ impl Clean for hir::Ty<'_> { Err(_) => cx .sess() .source_map() - .span_to_snippet(cx.tcx.def_span(def_id)) + .span_to_snippet(cx.tcx.real_def_span(def_id)) .unwrap_or_else(|_| "_".to_string()), }; Array(box ty.clean(cx), length) @@ -1951,6 +1951,12 @@ impl Clean for rustc_span::Span { } } +impl Clean for rustc_span::SpanId { + fn clean(&self, cx: &DocContext<'_>) -> Span { + cx.tcx.reify_span(*self).clean(cx) + } +} + impl Clean for hir::Path<'_> { fn clean(&self, cx: &DocContext<'_>) -> Path { Path { diff --git a/src/librustdoc/passes/check_code_block_syntax.rs b/src/librustdoc/passes/check_code_block_syntax.rs index d1f2c12ccd630..616c13c33e4e9 100644 --- a/src/librustdoc/passes/check_code_block_syntax.rs +++ b/src/librustdoc/passes/check_code_block_syntax.rs @@ -1,6 +1,6 @@ use rustc_ast::token; use rustc_data_structures::sync::{Lock, Lrc}; -use rustc_errors::{emitter::Emitter, Applicability, Diagnostic, Handler}; +use rustc_errors::{emitter::Emitter, Applicability, Handler, RealDiagnostic}; use rustc_parse::lexer::StringReader as Lexer; use rustc_session::parse::ParseSess; use rustc_span::source_map::{FilePathMapping, SourceMap}; @@ -130,7 +130,7 @@ struct BufferEmitter { } impl Emitter for BufferEmitter { - fn emit_diagnostic(&mut self, diag: &Diagnostic) { + fn emit_diagnostic(&mut self, diag: &RealDiagnostic) { self.messages.borrow_mut().push(format!("error from rustc: {}", diag.message[0].0)); } diff --git a/src/test/ui/consts/dangling-alloc-id-ice.stderr b/src/test/ui/consts/dangling-alloc-id-ice.stderr index 0e213555052c8..121211e79c854 100644 --- a/src/test/ui/consts/dangling-alloc-id-ice.stderr +++ b/src/test/ui/consts/dangling-alloc-id-ice.stderr @@ -5,7 +5,9 @@ LL | / const FOO: &() = { LL | | let y = (); LL | | unsafe { Foo { y: &y }.long_live_the_unit } LL | | }; - | |__^ encountered dangling pointer in final constant + | | ^ encountered dangling pointer in final constant + | |__| + | | = note: `#[deny(const_err)]` on by default diff --git a/src/test/ui/consts/dangling_raw_ptr.stderr b/src/test/ui/consts/dangling_raw_ptr.stderr index 4d4c2876c4598..ae911bd8e0d5e 100644 --- a/src/test/ui/consts/dangling_raw_ptr.stderr +++ b/src/test/ui/consts/dangling_raw_ptr.stderr @@ -5,7 +5,9 @@ LL | / const FOO: *const u32 = { LL | | let x = 42; LL | | &x LL | | }; - | |__^ encountered dangling pointer in final constant + | | ^ encountered dangling pointer in final constant + | |__| + | | = note: `#[deny(const_err)]` on by default diff --git a/src/test/ui/consts/miri_unleashed/mutable_const2.stderr b/src/test/ui/consts/miri_unleashed/mutable_const2.stderr index 98a1c8bdd8967..9d065be439f55 100644 --- a/src/test/ui/consts/miri_unleashed/mutable_const2.stderr +++ b/src/test/ui/consts/miri_unleashed/mutable_const2.stderr @@ -14,7 +14,7 @@ error: internal compiler error: mutable allocation in constant LL | const MUTABLE_BEHIND_RAW: *mut i32 = &UnsafeCell::new(42) as *const _ as *mut _; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -thread 'rustc' panicked at 'no errors encountered even though `delay_span_bug` issued', src/librustc_errors/lib.rs:366:17 +thread 'rustc' panicked at 'no errors encountered even though `delay_span_bug` issued', src/librustc_errors/lib.rs:399:17 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace error: internal compiler error: unexpected panic diff --git a/src/tools/clippy/clippy_lints/src/as_conversions.rs b/src/tools/clippy/clippy_lints/src/as_conversions.rs index 0c8efd755146e..0c2bb36b59aa9 100644 --- a/src/tools/clippy/clippy_lints/src/as_conversions.rs +++ b/src/tools/clippy/clippy_lints/src/as_conversions.rs @@ -40,7 +40,7 @@ declare_lint_pass!(AsConversions => [AS_CONVERSIONS]); impl EarlyLintPass for AsConversions { fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), expr.span.into()) { return; } diff --git a/src/tools/clippy/clippy_lints/src/attrs.rs b/src/tools/clippy/clippy_lints/src/attrs.rs index 64abc9fdc7174..74403bd0813e3 100644 --- a/src/tools/clippy/clippy_lints/src/attrs.rs +++ b/src/tools/clippy/clippy_lints/src/attrs.rs @@ -288,7 +288,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Attributes { let skip_unused_imports = item.attrs.iter().any(|attr| attr.check_name(sym!(macro_use))); for attr in item.attrs { - if in_external_macro(cx.sess(), attr.span) { + if in_external_macro(cx.sess(), attr.span.into()) { return; } if let Some(lint_list) = &attr.meta_item_list() { diff --git a/src/tools/clippy/clippy_lints/src/block_in_if_condition.rs b/src/tools/clippy/clippy_lints/src/block_in_if_condition.rs index 9e533eaa32c93..511a2dec3a93e 100644 --- a/src/tools/clippy/clippy_lints/src/block_in_if_condition.rs +++ b/src/tools/clippy/clippy_lints/src/block_in_if_condition.rs @@ -76,7 +76,7 @@ const COMPLEX_BLOCK_MESSAGE: &str = "in an `if` condition, avoid complex blocks impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BlockInIfCondition { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), expr.span.into()) { return; } if let Some((cond, _, _)) = higher::if_block(&expr) { diff --git a/src/tools/clippy/clippy_lints/src/checked_conversions.rs b/src/tools/clippy/clippy_lints/src/checked_conversions.rs index d9776dd50a836..2609fa75ceb55 100644 --- a/src/tools/clippy/clippy_lints/src/checked_conversions.rs +++ b/src/tools/clippy/clippy_lints/src/checked_conversions.rs @@ -44,7 +44,7 @@ declare_lint_pass!(CheckedConversions => [CHECKED_CONVERSIONS]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CheckedConversions { fn check_expr(&mut self, cx: &LateContext<'_, '_>, item: &Expr<'_>) { let result = if_chain! { - if !in_external_macro(cx.sess(), item.span); + if !in_external_macro(cx.sess(), item.span.into()); if let ExprKind::Binary(op, ref left, ref right) = &item.kind; then { diff --git a/src/tools/clippy/clippy_lints/src/doc.rs b/src/tools/clippy/clippy_lints/src/doc.rs index 8d1e91f9adbd6..b8ef9f92affe2 100644 --- a/src/tools/clippy/clippy_lints/src/doc.rs +++ b/src/tools/clippy/clippy_lints/src/doc.rs @@ -8,7 +8,7 @@ use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::lint::in_external_macro; use rustc_middle::ty; use rustc_session::{declare_tool_lint, impl_lint_pass}; -use rustc_span::source_map::{BytePos, MultiSpan, Span}; +use rustc_span::source_map::{BytePos, MultiSpanId, Span}; use rustc_span::Pos; use std::ops::Range; use url::Url; @@ -156,7 +156,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DocMarkdown { match item.kind { hir::ItemKind::Fn(ref sig, _, body_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.into())) { lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id)); } @@ -180,7 +180,7 @@ 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) { + if !in_external_macro(cx.tcx.sess, item.span.into()) { lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, None); } } @@ -188,7 +188,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DocMarkdown { 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) { + if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span.into()) { return; } if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind { @@ -200,7 +200,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DocMarkdown { fn lint_for_missing_headers<'a, 'tcx>( cx: &LateContext<'a, 'tcx>, hir_id: hir::HirId, - span: impl Into + Copy, + span: impl Into + Copy, sig: &hir::FnSig<'_>, headers: DocHeaders, body_id: Option, diff --git a/src/tools/clippy/clippy_lints/src/else_if_without_else.rs b/src/tools/clippy/clippy_lints/src/else_if_without_else.rs index 95123e6ff6fe2..274e5ce9d5de3 100644 --- a/src/tools/clippy/clippy_lints/src/else_if_without_else.rs +++ b/src/tools/clippy/clippy_lints/src/else_if_without_else.rs @@ -50,7 +50,7 @@ declare_lint_pass!(ElseIfWithoutElse => [ELSE_IF_WITHOUT_ELSE]); impl EarlyLintPass for ElseIfWithoutElse { fn check_expr(&mut self, cx: &EarlyContext<'_>, mut item: &Expr) { - if in_external_macro(cx.sess(), item.span) { + if in_external_macro(cx.sess(), item.span.into()) { return; } diff --git a/src/tools/clippy/clippy_lints/src/eta_reduction.rs b/src/tools/clippy/clippy_lints/src/eta_reduction.rs index e3e1136b67693..c542f4e3158ad 100644 --- a/src/tools/clippy/clippy_lints/src/eta_reduction.rs +++ b/src/tools/clippy/clippy_lints/src/eta_reduction.rs @@ -62,7 +62,7 @@ declare_lint_pass!(EtaReduction => [REDUNDANT_CLOSURE, REDUNDANT_CLOSURE_FOR_MET impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EtaReduction { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), expr.span.into()) { return; } diff --git a/src/tools/clippy/clippy_lints/src/formatting.rs b/src/tools/clippy/clippy_lints/src/formatting.rs index eb4b7a826f2ce..0577ce5d23f7d 100644 --- a/src/tools/clippy/clippy_lints/src/formatting.rs +++ b/src/tools/clippy/clippy_lints/src/formatting.rs @@ -205,7 +205,7 @@ fn check_else(cx: &EarlyContext<'_>, expr: &Expr) { if let ExprKind::If(_, then, Some(else_)) = &expr.kind; if is_block(else_) || is_if(else_); if !differing_macro_contexts(then.span, else_.span); - if !then.span.from_expansion() && !in_external_macro(cx.sess, expr.span); + if !then.span.from_expansion() && !in_external_macro(cx.sess, expr.span.into()); // workaround for rust-lang/rust#43081 if expr.span.lo().0 != 0 && expr.span.hi().0 != 0; diff --git a/src/tools/clippy/clippy_lints/src/functions.rs b/src/tools/clippy/clippy_lints/src/functions.rs index c24a24733d7f3..d9eb0812cf889 100644 --- a/src/tools/clippy/clippy_lints/src/functions.rs +++ b/src/tools/clippy/clippy_lints/src/functions.rs @@ -318,7 +318,7 @@ impl<'a, 'tcx> Functions { } fn check_line_number(self, cx: &LateContext<'_, '_>, span: Span, body: &'tcx hir::Body<'_>) { - if in_external_macro(cx.sess(), span) { + if in_external_macro(cx.sess(), span.into()) { return; } @@ -407,7 +407,7 @@ fn check_needless_must_use( fn_header_span: Span, attr: &Attribute, ) { - if in_external_macro(cx.sess(), item_span) { + if in_external_macro(cx.sess(), item_span.into()) { return; } if returns_unit(decl) { @@ -448,7 +448,7 @@ fn check_must_use_candidate<'a, 'tcx>( ) { if has_mutable_arg(cx, body) || mutates_static(cx, body) - || in_external_macro(cx.sess(), item_span) + || in_external_macro(cx.sess(), item_span.into()) || returns_unit(decl) || !cx.access_levels.is_exported(item_id) || is_must_use_ty(cx, return_ty(cx, item_id)) @@ -507,7 +507,7 @@ fn is_mutable_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>, span: Span, // primitive types are never mutable ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => false, ty::Adt(ref adt, ref substs) => { - tys.insert(adt.did) && !ty.is_freeze(cx.tcx, cx.param_env, span) + tys.insert(adt.did) && !ty.is_freeze(cx.tcx, cx.param_env, span.into()) || KNOWN_WRAPPER_TYS.iter().any(|path| match_def_path(cx, adt.did, path)) && substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys)) }, diff --git a/src/tools/clippy/clippy_lints/src/if_not_else.rs b/src/tools/clippy/clippy_lints/src/if_not_else.rs index c11e291f98e4b..1b71475a05d15 100644 --- a/src/tools/clippy/clippy_lints/src/if_not_else.rs +++ b/src/tools/clippy/clippy_lints/src/if_not_else.rs @@ -49,7 +49,7 @@ declare_lint_pass!(IfNotElse => [IF_NOT_ELSE]); impl EarlyLintPass for IfNotElse { fn check_expr(&mut self, cx: &EarlyContext<'_>, item: &Expr) { - if in_external_macro(cx.sess(), item.span) { + if in_external_macro(cx.sess(), item.span.into()) { return; } if let ExprKind::If(ref cond, _, Some(ref els)) = item.kind { 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 398a3103a0371..ec2600956074c 100644 --- a/src/tools/clippy/clippy_lints/src/let_if_seq.rs +++ b/src/tools/clippy/clippy_lints/src/let_if_seq.rs @@ -76,7 +76,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetIfSeq { let has_interior_mutability = !cx.tables.node_type(canonical_id).is_freeze( cx.tcx, cx.param_env, - span + span.into() ); if has_interior_mutability { return; } diff --git a/src/tools/clippy/clippy_lints/src/let_underscore.rs b/src/tools/clippy/clippy_lints/src/let_underscore.rs index 710dec8d33fc9..f0b7c529922b9 100644 --- a/src/tools/clippy/clippy_lints/src/let_underscore.rs +++ b/src/tools/clippy/clippy_lints/src/let_underscore.rs @@ -68,7 +68,7 @@ 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) { + if in_external_macro(cx.tcx.sess, local.span.into()) { return; } diff --git a/src/tools/clippy/clippy_lints/src/literal_representation.rs b/src/tools/clippy/clippy_lints/src/literal_representation.rs index ec7c4531ed716..39be223a3551e 100644 --- a/src/tools/clippy/clippy_lints/src/literal_representation.rs +++ b/src/tools/clippy/clippy_lints/src/literal_representation.rs @@ -176,7 +176,7 @@ declare_lint_pass!(LiteralDigitGrouping => [ impl EarlyLintPass for LiteralDigitGrouping { fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), expr.span.into()) { return; } @@ -350,7 +350,7 @@ impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION] impl EarlyLintPass for DecimalLiteralRepresentation { fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), expr.span.into()) { return; } diff --git a/src/tools/clippy/clippy_lints/src/loops.rs b/src/tools/clippy/clippy_lints/src/loops.rs index f7c7fd82d833b..636033bd92d62 100644 --- a/src/tools/clippy/clippy_lints/src/loops.rs +++ b/src/tools/clippy/clippy_lints/src/loops.rs @@ -528,7 +528,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Loops { && arms[1].guard.is_none() && is_simple_break_expr(&arms[1].body) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), expr.span.into()) { return; } diff --git a/src/tools/clippy/clippy_lints/src/match_on_vec_items.rs b/src/tools/clippy/clippy_lints/src/match_on_vec_items.rs index 4071406cc84c3..c41b3ae9fe662 100644 --- a/src/tools/clippy/clippy_lints/src/match_on_vec_items.rs +++ b/src/tools/clippy/clippy_lints/src/match_on_vec_items.rs @@ -47,7 +47,7 @@ declare_lint_pass!(MatchOnVecItems => [MATCH_ON_VEC_ITEMS]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchOnVecItems { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) { if_chain! { - if !in_external_macro(cx.sess(), expr.span); + if !in_external_macro(cx.sess(), expr.span.into()); if let ExprKind::Match(ref match_expr, _, MatchSource::Normal) = expr.kind; if let Some(idx_expr) = is_vec_indexing(cx, match_expr); if let ExprKind::Index(vec, idx) = idx_expr.kind; diff --git a/src/tools/clippy/clippy_lints/src/matches.rs b/src/tools/clippy/clippy_lints/src/matches.rs index 8f86535ef1e0f..c2f890d3c560d 100644 --- a/src/tools/clippy/clippy_lints/src/matches.rs +++ b/src/tools/clippy/clippy_lints/src/matches.rs @@ -364,7 +364,7 @@ impl_lint_pass!(Matches => [ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Matches { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), expr.span.into()) { return; } if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.kind { @@ -389,7 +389,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Matches { fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local<'_>) { if_chain! { - if !in_external_macro(cx.sess(), local.span); + if !in_external_macro(cx.sess(), local.span.into()); if !in_macro(local.span); if let Some(ref expr) = local.init; if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.kind; @@ -425,7 +425,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Matches { fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat<'_>) { if_chain! { - if !in_external_macro(cx.sess(), pat.span); + if !in_external_macro(cx.sess(), pat.span.into()); if !in_macro(pat.span); if let PatKind::Struct(ref qpath, fields, true) = pat.kind; if let QPath::Resolved(_, ref path) = qpath; diff --git a/src/tools/clippy/clippy_lints/src/mem_replace.rs b/src/tools/clippy/clippy_lints/src/mem_replace.rs index ab6865bf0f3b7..1d7545c3d744b 100644 --- a/src/tools/clippy/clippy_lints/src/mem_replace.rs +++ b/src/tools/clippy/clippy_lints/src/mem_replace.rs @@ -170,7 +170,7 @@ fn check_replace_with_uninit(cx: &LateContext<'_, '_>, src: &Expr<'_>, expr_span fn check_replace_with_default(cx: &LateContext<'_, '_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) { if let ExprKind::Call(ref repl_func, _) = src.kind { if_chain! { - if !in_external_macro(cx.tcx.sess, expr_span); + if !in_external_macro(cx.tcx.sess, expr_span.into()); if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind; if let Some(repl_def_id) = cx.tables.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id(); if match_def_path(cx, repl_def_id, &paths::DEFAULT_TRAIT_METHOD); diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index 3676dc5b09d21..b99d9a8f377d0 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -1450,7 +1450,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(), impl_item.span.into()) { return; } let name = impl_item.ident.name.as_str(); diff --git a/src/tools/clippy/clippy_lints/src/misc_early.rs b/src/tools/clippy/clippy_lints/src/misc_early.rs index adfd8dfb1c18a..62609f5630827 100644 --- a/src/tools/clippy/clippy_lints/src/misc_early.rs +++ b/src/tools/clippy/clippy_lints/src/misc_early.rs @@ -412,7 +412,7 @@ impl EarlyLintPass for MiscEarlyLints { } fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), expr.span.into()) { return; } match expr.kind { 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 4301157e16440..f9bede6e47fce 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 @@ -83,7 +83,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingConstForFn { ) { let def_id = cx.tcx.hir().local_def_id(hir_id); - if in_external_macro(cx.tcx.sess, span) || is_entrypoint_fn(cx, def_id.to_def_id()) { + if in_external_macro(cx.tcx.sess, span.into()) || is_entrypoint_fn(cx, def_id.to_def_id()) { return; } diff --git a/src/tools/clippy/clippy_lints/src/missing_inline.rs b/src/tools/clippy/clippy_lints/src/missing_inline.rs index 5300fd2215b39..2c127a3956d10 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(), it.span.into()) || is_executable(cx) { return; } @@ -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(), impl_item.span.into()) || is_executable(cx) { return; } diff --git a/src/tools/clippy/clippy_lints/src/mut_key.rs b/src/tools/clippy/clippy_lints/src/mut_key.rs index 0b9b7e1b8cc1b..edae037a46768 100644 --- a/src/tools/clippy/clippy_lints/src/mut_key.rs +++ b/src/tools/clippy/clippy_lints/src/mut_key.rs @@ -118,7 +118,7 @@ fn is_mutable_type<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>, span: Spa size.try_eval_usize(cx.tcx, cx.param_env).map_or(true, |u| u != 0) && is_mutable_type(cx, inner_ty, span) }, Tuple(..) => ty.tuple_fields().any(|ty| is_mutable_type(cx, ty, span)), - Adt(..) => cx.tcx.layout_of(cx.param_env.and(ty)).is_ok() && !ty.is_freeze(cx.tcx, cx.param_env, span), + Adt(..) => cx.tcx.layout_of(cx.param_env.and(ty)).is_ok() && !ty.is_freeze(cx.tcx, cx.param_env, span.into()), _ => false, } } diff --git a/src/tools/clippy/clippy_lints/src/mut_mut.rs b/src/tools/clippy/clippy_lints/src/mut_mut.rs index f7a20a74b85e2..f9cfb5b158815 100644 --- a/src/tools/clippy/clippy_lints/src/mut_mut.rs +++ b/src/tools/clippy/clippy_lints/src/mut_mut.rs @@ -48,7 +48,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> { type Map = Map<'tcx>; fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) { - if in_external_macro(self.cx.sess(), expr.span) { + if in_external_macro(self.cx.sess(), expr.span.into()) { return; } diff --git a/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs b/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs index 54536ed57d3e9..164c0d057ecb7 100644 --- a/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs +++ b/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs @@ -49,7 +49,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NoNegCompOpForPartialOrd { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) { if_chain! { - if !in_external_macro(cx.sess(), expr.span); + if !in_external_macro(cx.sess(), expr.span.into()); if let ExprKind::Unary(UnOp::UnNot, ref inner) = expr.kind; if let ExprKind::Binary(ref op, ref left, _) = inner.kind; if let BinOpKind::Le | BinOpKind::Ge | BinOpKind::Lt | BinOpKind::Gt = op.node; 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 a599667b8d8a8..d3e49c01ca78d 100644 --- a/src/tools/clippy/clippy_lints/src/new_without_default.rs +++ b/src/tools/clippy/clippy_lints/src/new_without_default.rs @@ -102,7 +102,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(), impl_item.span.into()) { return; } if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind { @@ -227,7 +227,7 @@ fn can_derive_default<'t, 'c>(ty: Ty<'t>, cx: &LateContext<'c, 't>, default_trai return None; } } - Some(cx.tcx.def_span(adt_def.did)) + Some(cx.tcx.real_def_span(adt_def.did)) }, _ => None, } 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..1287b681cf195 100644 --- a/src/tools/clippy/clippy_lints/src/non_copy_const.rs +++ b/src/tools/clippy/clippy_lints/src/non_copy_const.rs @@ -10,7 +10,7 @@ use rustc_lint::{LateContext, LateLintPass, Lint}; use rustc_middle::ty::adjustment::Adjust; use rustc_middle::ty::{Ty, TypeFlags}; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::{InnerSpan, Span, DUMMY_SP}; +use rustc_span::{InnerSpan, Span, DUMMY_SPID}; use rustc_typeck::hir_ty_to_ty; use crate::utils::{in_constant, is_copy, qpath_res, span_lint_and_then}; @@ -110,7 +110,7 @@ impl Source { } fn verify_ty_bound<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>, source: Source) { - if ty.is_freeze(cx.tcx, cx.param_env, DUMMY_SP) || is_copy(cx, ty) { + if ty.is_freeze(cx.tcx, cx.param_env, DUMMY_SPID) || is_copy(cx, ty) { // An `UnsafeCell` is `!Copy`, and an `UnsafeCell` is also the only type which // is `!Freeze`, thus if our type is `Copy` we can be sure it must be `Freeze` // as well. diff --git a/src/tools/clippy/clippy_lints/src/question_mark.rs b/src/tools/clippy/clippy_lints/src/question_mark.rs index ea654467b8668..98db6def5bf49 100644 --- a/src/tools/clippy/clippy_lints/src/question_mark.rs +++ b/src/tools/clippy/clippy_lints/src/question_mark.rs @@ -137,7 +137,7 @@ impl QuestionMark { fn moves_by_default(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool { let expr_ty = cx.tables.expr_ty(expression); - !expr_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, expression.span) + !expr_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, expression.span.into()) } fn is_option(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool { diff --git a/src/tools/clippy/clippy_lints/src/redundant_clone.rs b/src/tools/clippy/clippy_lints/src/redundant_clone.rs index d563eb886ae7e..3be625d503ee2 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_clone.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_clone.rs @@ -99,7 +99,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone { for (bb, bbdata) in mir.basic_blocks().iter_enumerated() { let terminator = bbdata.terminator(); - if terminator.source_info.span.from_expansion() { + let span = cx.tcx.reify_span(terminator.source_info.span); + if span.from_expansion() { continue; } @@ -217,7 +218,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone { ); if !used || !consumed_or_mutated { - let span = terminator.source_info.span; let scope = terminator.source_info.scope; let node = mir.source_scopes[scope] .local_data diff --git a/src/tools/clippy/clippy_lints/src/returns.rs b/src/tools/clippy/clippy_lints/src/returns.rs index 5c9117d5b81cd..f6d930dfd6bf0 100644 --- a/src/tools/clippy/clippy_lints/src/returns.rs +++ b/src/tools/clippy/clippy_lints/src/returns.rs @@ -150,7 +150,7 @@ impl Return { fn emit_return_lint(cx: &EarlyContext<'_>, ret_span: Span, inner_span: Option, replacement: RetReplacement) { match inner_span { Some(inner_span) => { - if in_external_macro(cx.sess(), inner_span) || inner_span.from_expansion() { + if in_external_macro(cx.sess(), inner_span.into()) || inner_span.from_expansion() { return; } @@ -204,9 +204,9 @@ impl Return { if let ast::PatKind::Ident(_, ident, _) = local.pat.kind; if let ast::ExprKind::Path(_, ref path) = retexpr.kind; if match_path_ast(path, &[&*ident.name.as_str()]); - 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_external_macro(cx.sess(), initexpr.span.into()); + if !in_external_macro(cx.sess(), retexpr.span.into()); + if !in_external_macro(cx.sess(), local.span.into()); if !in_macro(local.span); then { span_lint_and_then( diff --git a/src/tools/clippy/clippy_lints/src/shadow.rs b/src/tools/clippy/clippy_lints/src/shadow.rs index 11360b0ef8495..ad4ce1a4907d1 100644 --- a/src/tools/clippy/clippy_lints/src/shadow.rs +++ b/src/tools/clippy/clippy_lints/src/shadow.rs @@ -96,7 +96,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Shadow { _: Span, _: HirId, ) { - if in_external_macro(cx.sess(), body.value.span) { + if in_external_macro(cx.sess(), body.value.span.into()) { return; } check_fn(cx, decl, body); @@ -129,7 +129,7 @@ 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) { + if in_external_macro(cx.sess(), local.span.into()) { return; } if higher::is_from_for_desugar(local) { @@ -317,7 +317,7 @@ fn lint_shadow<'a, 'tcx>( } fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>, bindings: &mut Vec<(Name, Span)>) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), expr.span.into()) { return; } match expr.kind { diff --git a/src/tools/clippy/clippy_lints/src/strings.rs b/src/tools/clippy/clippy_lints/src/strings.rs index 2c51271e312de..65ec603cf3a92 100644 --- a/src/tools/clippy/clippy_lints/src/strings.rs +++ b/src/tools/clippy/clippy_lints/src/strings.rs @@ -80,7 +80,7 @@ declare_lint_pass!(StringAdd => [STRING_ADD, STRING_ADD_ASSIGN]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringAdd { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) { - if in_external_macro(cx.sess(), e.span) { + if in_external_macro(cx.sess(), e.span.into()) { return; } diff --git a/src/tools/clippy/clippy_lints/src/transmuting_null.rs b/src/tools/clippy/clippy_lints/src/transmuting_null.rs index 1d0332c580500..3792756705634 100644 --- a/src/tools/clippy/clippy_lints/src/transmuting_null.rs +++ b/src/tools/clippy/clippy_lints/src/transmuting_null.rs @@ -31,7 +31,7 @@ const LINT_MSG: &str = "transmuting a known null pointer into a reference."; impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TransmutingNull { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) { - if in_external_macro(cx.sess(), expr.span) { + if in_external_macro(cx.sess(), expr.span.into()) { return; } diff --git a/src/tools/clippy/clippy_lints/src/try_err.rs b/src/tools/clippy/clippy_lints/src/try_err.rs index 7018fa6804ba7..7bd46a40a2c5f 100644 --- a/src/tools/clippy/clippy_lints/src/try_err.rs +++ b/src/tools/clippy/clippy_lints/src/try_err.rs @@ -55,7 +55,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TryErr { // val, // }; if_chain! { - if !in_external_macro(cx.tcx.sess, expr.span); + if !in_external_macro(cx.tcx.sess, expr.span.into()); if let ExprKind::Match(ref match_arg, _, MatchSource::TryDesugar) = expr.kind; if let ExprKind::Call(ref match_fun, ref try_args) = match_arg.kind; if let ExprKind::Path(ref match_fun_path) = match_fun.kind; diff --git a/src/tools/clippy/clippy_lints/src/types.rs b/src/tools/clippy/clippy_lints/src/types.rs index 6d49f50d550e8..8a630e71a377b 100644 --- a/src/tools/clippy/clippy_lints/src/types.rs +++ b/src/tools/clippy/clippy_lints/src/types.rs @@ -604,7 +604,7 @@ 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() { + if in_external_macro(cx.sess(), stmt.span.into()) || local.pat.span.from_expansion() { return; } if higher::is_from_for_desugar(local) { @@ -1349,7 +1349,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Casts { match lit.node { LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {}, _ => { - if cast_from.kind == cast_to.kind && !in_external_macro(cx.sess(), expr.span) { + if cast_from.kind == cast_to.kind && !in_external_macro(cx.sess(), expr.span.into()) { span_lint( cx, UNNECESSARY_CAST, @@ -1363,7 +1363,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Casts { }, } } - if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) { + if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span.into()) { lint_numeric_casts(cx, expr, ex, cast_from, cast_to); } @@ -2290,7 +2290,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher { vis.visit_ty(ty); for target in &vis.found { - if in_external_macro(cx.sess(), generics.span) { + if in_external_macro(cx.sess(), generics.span.into()) { continue; } let generics_suggestion_span = generics.span.substitute_dummy({ diff --git a/src/tools/clippy/clippy_lints/src/unwrap.rs b/src/tools/clippy/clippy_lints/src/unwrap.rs index 5235c98efab13..4ff49681c060f 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap.rs @@ -140,7 +140,7 @@ impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> { fn visit_expr(&mut self, expr: &'tcx Expr<'_>) { // Shouldn't lint when `expr` is in macro. - if in_external_macro(self.cx.tcx.sess, expr.span) { + if in_external_macro(self.cx.tcx.sess, expr.span.into()) { return; } if let Some((cond, then, els)) = if_block(&expr) { diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index f8e1aff33e773..f1ce6f02ee6ff 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(), item.span.into()) { return; } if_chain! { diff --git a/src/tools/clippy/clippy_lints/src/utils/diagnostics.rs b/src/tools/clippy/clippy_lints/src/utils/diagnostics.rs index 24a1bdf1883f6..24f1912b26a31 100644 --- a/src/tools/clippy/clippy_lints/src/utils/diagnostics.rs +++ b/src/tools/clippy/clippy_lints/src/utils/diagnostics.rs @@ -3,7 +3,7 @@ use rustc_errors::{Applicability, CodeSuggestion, DiagnosticBuilder, Substitution, SubstitutionPart, SuggestionStyle}; use rustc_hir::HirId; use rustc_lint::{LateContext, Lint, LintContext}; -use rustc_span::source_map::{MultiSpan, Span}; +use rustc_span::source_map::{MultiSpanId, Span}; use std::env; fn docs_link(diag: &mut DiagnosticBuilder<'_>, lint: &'static Lint) { @@ -36,7 +36,7 @@ fn docs_link(diag: &mut DiagnosticBuilder<'_>, lint: &'static Lint) { /// 17 | std::mem::forget(seven); /// | ^^^^^^^^^^^^^^^^^^^^^^^ /// ``` -pub fn span_lint(cx: &T, lint: &'static Lint, sp: impl Into, msg: &str) { +pub fn span_lint(cx: &T, lint: &'static Lint, sp: impl Into, msg: &str) { cx.struct_span_lint(lint, sp, |diag| { let mut diag = diag.build(msg); docs_link(&mut diag, lint); @@ -206,7 +206,7 @@ where substitutions: vec![Substitution { parts: sugg .into_iter() - .map(|(span, snippet)| SubstitutionPart { snippet, span }) + .map(|(span, snippet)| SubstitutionPart { snippet, span: span.into() }) .collect(), }], msg: help_msg, diff --git a/src/tools/clippy/clippy_lints/src/utils/mod.rs b/src/tools/clippy/clippy_lints/src/utils/mod.rs index 2fd080e9ef0f8..2606d3efbb647 100644 --- a/src/tools/clippy/clippy_lints/src/utils/mod.rs +++ b/src/tools/clippy/clippy_lints/src/utils/mod.rs @@ -45,7 +45,7 @@ use rustc_middle::ty::{self, layout::IntegerExt, subst::GenericArg, Binder, Ty, use rustc_span::hygiene::{ExpnKind, MacroKind}; use rustc_span::source_map::original_sp; use rustc_span::symbol::{self, kw, Symbol}; -use rustc_span::{BytePos, Pos, Span, DUMMY_SP}; +use rustc_span::{BytePos, Pos, Span, DUMMY_SP, DUMMY_SPID}; use rustc_target::abi::Integer; use rustc_trait_selection::traits::predicate_for_trait_def; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; @@ -914,7 +914,7 @@ pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx } pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { - ty.is_copy_modulo_regions(cx.tcx, cx.param_env, DUMMY_SP) + ty.is_copy_modulo_regions(cx.tcx, cx.param_env, DUMMY_SPID) } /// Checks if an expression is constructing a tuple-like enum variant or struct diff --git a/src/tools/clippy/src/driver.rs b/src/tools/clippy/src/driver.rs index 2c699998ea90e..bba4d9dedb4e9 100644 --- a/src/tools/clippy/src/driver.rs +++ b/src/tools/clippy/src/driver.rs @@ -258,7 +258,7 @@ fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) { // it wants to print. if !info.payload().is::() { let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic"); - handler.emit_diagnostic(&d); + handler.emit_diagnostic(d); } let version_info = rustc_tools_util::get_version_info!();