1
Fork 0

Use local and remapped paths where appropriate

This commit is contained in:
Andy Wang 2021-04-19 23:27:02 +01:00
parent fb4f6439f6
commit 5417b45c26
No known key found for this signature in database
GPG key ID: 181B49F9F38F3374
28 changed files with 85 additions and 74 deletions

View file

@ -61,7 +61,9 @@ pub fn expand_file(
let topmost = cx.expansion_cause().unwrap_or(sp); let topmost = cx.expansion_cause().unwrap_or(sp);
let loc = cx.source_map().lookup_char_pos(topmost.lo()); let loc = cx.source_map().lookup_char_pos(topmost.lo());
base::MacEager::expr(cx.expr_str(topmost, Symbol::intern(&loc.file.name.to_string()))) base::MacEager::expr(
cx.expr_str(topmost, Symbol::intern(&loc.file.name.prefer_remapped().to_string_lossy())),
)
} }
pub fn expand_stringify( pub fn expand_stringify(

View file

@ -334,7 +334,9 @@ impl<'tcx> FunctionCx<'_, '_, 'tcx> {
let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span); let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo()); let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
let const_loc = self.tcx.const_caller_location(( let const_loc = self.tcx.const_caller_location((
rustc_span::symbol::Symbol::intern(&caller.file.name.to_string()), rustc_span::symbol::Symbol::intern(
&caller.file.name.prefer_remapped().to_string_lossy(),
),
caller.line as u32, caller.line as u32,
caller.col_display as u32 + 1, caller.col_display as u32 + 1,
)); ));

View file

@ -87,7 +87,7 @@ fn line_program_add_file(
filename => { filename => {
let dir_id = line_program.default_directory(); let dir_id = line_program.default_directory();
let dummy_file_name = LineString::new( let dummy_file_name = LineString::new(
filename.to_string().into_bytes(), filename.prefer_remapped().to_string().into_bytes(),
line_program.encoding(), line_program.encoding(),
line_strings, line_strings,
); );

View file

@ -759,10 +759,10 @@ fn hex_encode(data: &[u8]) -> String {
} }
pub fn file_metadata(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile { pub fn file_metadata(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
debug!("file_metadata: file_name: {}", source_file.name); debug!("file_metadata: file_name: {:?}", source_file.name);
let hash = Some(&source_file.src_hash); let hash = Some(&source_file.src_hash);
let file_name = Some(source_file.name.to_string()); let file_name = Some(source_file.name.prefer_remapped().to_string());
let directory = if source_file.is_real_file() && !source_file.is_imported() { let directory = if source_file.is_real_file() && !source_file.is_imported() {
Some(cx.sess().working_dir.to_string_lossy(false).to_string()) Some(cx.sess().working_dir.to_string_lossy(false).to_string())
} else { } else {

View file

@ -1144,7 +1144,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span); let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
let caller = tcx.sess.source_map().lookup_char_pos(topmost.lo()); let caller = tcx.sess.source_map().lookup_char_pos(topmost.lo());
let const_loc = tcx.const_caller_location(( let const_loc = tcx.const_caller_location((
Symbol::intern(&caller.file.name.to_string()), Symbol::intern(&caller.file.name.prefer_remapped().to_string_lossy()),
caller.line as u32, caller.line as u32,
caller.col_display as u32 + 1, caller.col_display as u32 + 1,
)); ));

View file

@ -126,7 +126,8 @@ impl AnnotateSnippetEmitterWriter {
} }
// owned: line source, line index, annotations // owned: line source, line index, annotations
type Owned = (String, usize, Vec<crate::snippet::Annotation>); type Owned = (String, usize, Vec<crate::snippet::Annotation>);
let origin = primary_lo.file.name.to_string(); let filename = primary_lo.file.name.prefer_local();
let origin = filename.to_string_lossy();
let annotated_files: Vec<Owned> = annotated_files let annotated_files: Vec<Owned> = annotated_files
.into_iter() .into_iter()
.flat_map(|annotated_file| { .flat_map(|annotated_file| {

View file

@ -1309,7 +1309,7 @@ impl EmitterWriter {
buffer_msg_line_offset, buffer_msg_line_offset,
&format!( &format!(
"{}:{}:{}", "{}:{}:{}",
loc.file.name, loc.file.name.prefer_local(),
sm.doctest_offset_line(&loc.file.name, loc.line), sm.doctest_offset_line(&loc.file.name, loc.line),
loc.col.0 + 1, loc.col.0 + 1,
), ),
@ -1323,7 +1323,7 @@ impl EmitterWriter {
0, 0,
&format!( &format!(
"{}:{}:{}: ", "{}:{}:{}: ",
loc.file.name, loc.file.name.prefer_local(),
sm.doctest_offset_line(&loc.file.name, loc.line), sm.doctest_offset_line(&loc.file.name, loc.line),
loc.col.0 + 1, loc.col.0 + 1,
), ),
@ -1347,12 +1347,12 @@ impl EmitterWriter {
}; };
format!( format!(
"{}:{}{}", "{}:{}{}",
annotated_file.file.name, annotated_file.file.name.prefer_local(),
sm.doctest_offset_line(&annotated_file.file.name, first_line.line_index), sm.doctest_offset_line(&annotated_file.file.name, first_line.line_index),
col col
) )
} else { } else {
annotated_file.file.name.to_string() format!("{}", annotated_file.file.name.prefer_local())
}; };
buffer.append(buffer_msg_line_offset + 1, &loc, Style::LineAndColumn); buffer.append(buffer_msg_line_offset + 1, &loc, Style::LineAndColumn);
for _ in 0..max_line_num_len { for _ in 0..max_line_num_len {

View file

@ -468,7 +468,7 @@ impl DiagnosticSpan {
}); });
DiagnosticSpan { DiagnosticSpan {
file_name: start.file.name.to_string(), file_name: start.file.name.prefer_local().to_string(),
byte_start: start.file.original_relative_byte_pos(span.lo()).0, byte_start: start.file.original_relative_byte_pos(span.lo()).0,
byte_end: start.file.original_relative_byte_pos(span.hi()).0, byte_end: start.file.original_relative_byte_pos(span.hi()).0,
line_start: start.line, line_start: start.line,

View file

@ -1080,7 +1080,10 @@ impl<'a> ExtCtxt<'a> {
other => { other => {
return Err(self.struct_span_err( return Err(self.struct_span_err(
span, span,
&format!("cannot resolve relative path in non-file source `{}`", other), &format!(
"cannot resolve relative path in non-file source `{}`",
other.prefer_local()
),
)); ));
} }
}; };

View file

@ -365,7 +365,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
FileName::Real(name) => name FileName::Real(name) => name
.into_local_path() .into_local_path()
.expect("attempting to resolve a file path in an external file"), .expect("attempting to resolve a file path in an external file"),
other => PathBuf::from(other.to_string()), other => PathBuf::from(other.prefer_local().to_string()),
}; };
let dir_path = file_path.parent().unwrap_or(&file_path).to_owned(); let dir_path = file_path.parent().unwrap_or(&file_path).to_owned();
self.cx.root_path = dir_path.clone(); self.cx.root_path = dir_path.clone();

View file

@ -627,7 +627,7 @@ impl server::SourceFile for Rustc<'_> {
.to_str() .to_str()
.expect("non-UTF8 file path in `proc_macro::SourceFile::path`") .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
.to_string(), .to_string(),
_ => file.name.to_string(), _ => file.name.prefer_local().to_string(),
} }
} }
fn is_real(&mut self, file: &Self::SourceFile) -> bool { fn is_real(&mut self, file: &Self::SourceFile) -> bool {

View file

@ -1604,13 +1604,19 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
match (&terr, expected == found) { match (&terr, expected == found) {
(TypeError::Sorts(values), extra) => { (TypeError::Sorts(values), extra) => {
let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) { let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
(true, ty::Opaque(def_id, _)) => format!( (true, ty::Opaque(def_id, _)) => {
" (opaque type at {})", let pos = self
self.tcx .tcx
.sess .sess
.source_map() .source_map()
.mk_substr_filename(self.tcx.def_span(*def_id)), .lookup_char_pos(self.tcx.def_span(*def_id).lo());
), format!(
" (opaque type at <{}:{}:{}>)",
pos.file.name.prefer_local(),
pos.line,
pos.col.to_usize() + 1,
)
}
(true, _) => format!(" ({})", ty.sort_string(self.tcx)), (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
(false, _) => "".to_string(), (false, _) => "".to_string(),
}; };

View file

@ -36,7 +36,6 @@ use rustc_session::output::{filename_for_input, filename_for_metadata};
use rustc_session::search_paths::PathKind; use rustc_session::search_paths::PathKind;
use rustc_session::Session; use rustc_session::Session;
use rustc_span::symbol::{Ident, Symbol}; use rustc_span::symbol::{Ident, Symbol};
use rustc_span::FileName;
use rustc_trait_selection::traits; use rustc_trait_selection::traits;
use rustc_typeck as typeck; use rustc_typeck as typeck;
use tracing::{info, warn}; use tracing::{info, warn};
@ -575,14 +574,7 @@ fn write_out_deps(
.iter() .iter()
.filter(|fmap| fmap.is_real_file()) .filter(|fmap| fmap.is_real_file())
.filter(|fmap| !fmap.is_imported()) .filter(|fmap| !fmap.is_imported())
.map(|fmap| { .map(|fmap| escape_dep_filename(&fmap.name.prefer_local().to_string()))
escape_dep_filename(&match &fmap.name {
FileName::Real(real) => {
real.local_path().unwrap_or(real.stable_name()).display().to_string()
}
_ => fmap.name.to_string(),
})
})
.collect(); .collect();
if let Some(ref backend) = sess.opts.debugging_opts.codegen_backend { if let Some(ref backend) = sess.opts.debugging_opts.codegen_backend {

View file

@ -263,7 +263,13 @@ impl<'tcx> fmt::Display for FrameInfo<'tcx> {
} }
if !self.span.is_dummy() { if !self.span.is_dummy() {
let lo = tcx.sess.source_map().lookup_char_pos(self.span.lo()); let lo = tcx.sess.source_map().lookup_char_pos(self.span.lo());
write!(f, " at {}:{}:{}", lo.file.name, lo.line, lo.col.to_usize() + 1)?; write!(
f,
" at {}:{}:{}",
lo.file.name.prefer_local(),
lo.line,
lo.col.to_usize() + 1
)?;
} }
Ok(()) Ok(())
}) })

View file

@ -106,7 +106,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span); let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo()); let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
( (
Symbol::intern(&caller.file.name.to_string()), Symbol::intern(&caller.file.name.prefer_remapped().to_string_lossy()),
u32::try_from(caller.line).unwrap(), u32::try_from(caller.line).unwrap(),
u32::try_from(caller.col_display).unwrap().checked_add(1).unwrap(), u32::try_from(caller.col_display).unwrap().checked_add(1).unwrap(),
) )

View file

@ -290,7 +290,7 @@ impl<'a, 'tcx> Instrumentor<'a, 'tcx> {
let tcx = self.tcx; let tcx = self.tcx;
let source_map = tcx.sess.source_map(); let source_map = tcx.sess.source_map();
let body_span = self.body_span; let body_span = self.body_span;
let file_name = Symbol::intern(&self.source_file.name.to_string()); let file_name = Symbol::intern(&self.source_file.name.prefer_remapped().to_string_lossy());
let mut bcb_counters = IndexVec::from_elem_n(None, self.basic_coverage_blocks.num_nodes()); let mut bcb_counters = IndexVec::from_elem_n(None, self.basic_coverage_blocks.num_nodes());
for covspan in coverage_spans { for covspan in coverage_spans {

View file

@ -188,8 +188,10 @@ pub fn maybe_file_to_stream(
override_span: Option<Span>, override_span: Option<Span>,
) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> { ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
let src = source_file.src.as_ref().unwrap_or_else(|| { let src = source_file.src.as_ref().unwrap_or_else(|| {
sess.span_diagnostic sess.span_diagnostic.bug(&format!(
.bug(&format!("cannot lex `source_file` without source: {}", source_file.name)); "cannot lex `source_file` without source: {}",
source_file.name.prefer_local()
));
}); });
let (token_trees, unmatched_braces) = let (token_trees, unmatched_braces) =

View file

@ -1112,7 +1112,7 @@ impl<'tcx> DumpVisitor<'tcx> {
name: String::new(), name: String::new(),
qualname, qualname,
span, span,
value: filename.to_string(), value: filename.prefer_remapped().to_string(),
children, children,
parent: None, parent: None,
decl_id: None, decl_id: None,

View file

@ -80,7 +80,7 @@ impl<'tcx> SaveContext<'tcx> {
let end = sm.lookup_char_pos(span.hi()); let end = sm.lookup_char_pos(span.hi());
SpanData { SpanData {
file_name: start.file.name.to_string().into(), file_name: start.file.name.prefer_remapped().to_string().into(),
byte_start: span.lo().0, byte_start: span.lo().0,
byte_end: span.hi().0, byte_end: span.hi().0,
line_start: Row::new_one_indexed(start.line as u32), line_start: Row::new_one_indexed(start.line as u32),
@ -290,7 +290,7 @@ impl<'tcx> SaveContext<'tcx> {
name: item.ident.to_string(), name: item.ident.to_string(),
qualname, qualname,
span: self.span_from_span(item.ident.span), span: self.span_from_span(item.ident.span),
value: filename.to_string(), value: filename.prefer_remapped().to_string(),
parent: None, parent: None,
children: m children: m
.item_ids .item_ids

View file

@ -34,12 +34,7 @@ impl<'a> SpanUtils<'a> {
.to_string() .to_string()
} }
} }
// If the file name was remapped, we assume the user filename => filename.prefer_remapped().to_string(),
// configured it the way they wanted to, so use that directly
FileName::Real(RealFileName::Remapped { local_path: _, virtual_name }) => {
virtual_name.display().to_string()
}
filename => filename.to_string(),
} }
} }

View file

@ -305,6 +305,16 @@ impl FileName {
} }
} }
pub fn prefer_remapped(&self) -> FileNameDisplay<'_> {
FileNameDisplay { inner: self, prefer_local: false }
}
// This may include transient local filesystem information.
// Must not be embedded in build outputs.
pub fn prefer_local(&self) -> FileNameDisplay<'_> {
FileNameDisplay { inner: self, prefer_local: true }
}
pub fn macro_expansion_source_code(src: &str) -> FileName { pub fn macro_expansion_source_code(src: &str) -> FileName {
let mut hasher = StableHasher::new(); let mut hasher = StableHasher::new();
src.hash(&mut hasher); src.hash(&mut hasher);

View file

@ -369,11 +369,6 @@ impl SourceMap {
source_file source_file
} }
pub fn mk_substr_filename(&self, sp: Span) -> String {
let pos = self.lookup_char_pos(sp.lo());
format!("<{}:{}:{}>", pos.file.name, pos.line, pos.col.to_usize() + 1)
}
// If there is a doctest offset, applies it to the line. // If there is a doctest offset, applies it to the line.
pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize { pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
match file { match file {
@ -420,7 +415,7 @@ impl SourceMap {
let hi = self.lookup_char_pos(sp.hi()); let hi = self.lookup_char_pos(sp.hi());
format!( format!(
"{}:{}:{}: {}:{}", "{}:{}:{}: {}:{}",
lo.file.name, lo.file.name.prefer_remapped(),
lo.line, lo.line,
lo.col.to_usize() + 1, lo.col.to_usize() + 1,
hi.line, hi.line,

View file

@ -93,7 +93,7 @@ impl ExternalCrate {
crate fn src_root(&self, tcx: TyCtxt<'_>) -> PathBuf { crate fn src_root(&self, tcx: TyCtxt<'_>) -> PathBuf {
match self.src(tcx) { match self.src(tcx) {
FileName::Real(ref p) => match p.local_path().parent() { FileName::Real(ref p) => match p.local_path_if_available().parent() {
Some(p) => p.to_path_buf(), Some(p) => p.to_path_buf(),
None => PathBuf::new(), None => PathBuf::new(),
}, },

View file

@ -840,7 +840,7 @@ impl Collector {
if !item_path.is_empty() { if !item_path.is_empty() {
item_path.push(' '); item_path.push(' ');
} }
format!("{} - {}(line {})", filename, item_path, line) format!("{} - {}(line {})", filename.prefer_local(), item_path, line)
} }
crate fn set_position(&mut self, position: Span) { crate fn set_position(&mut self, position: Span) {
@ -891,7 +891,7 @@ impl Tester for Collector {
local_path.to_path_buf() local_path.to_path_buf()
} else { } else {
// Somehow we got the filename from the metadata of another crate, should never happen // Somehow we got the filename from the metadata of another crate, should never happen
PathBuf::from(r"doctest.rs") unreachable!("doctest from a different crate");
} }
} }
_ => PathBuf::from(r"doctest.rs"), _ => PathBuf::from(r"doctest.rs"),
@ -899,7 +899,8 @@ impl Tester for Collector {
// For example `module/file.rs` would become `module_file_rs` // For example `module/file.rs` would become `module_file_rs`
let file = filename let file = filename
.to_string() .prefer_local()
.to_string_lossy()
.chars() .chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect::<String>(); .collect::<String>();

View file

@ -376,17 +376,10 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
} = options; } = options;
let src_root = match krate.src { let src_root = match krate.src {
FileName::Real(ref p) => { FileName::Real(ref p) => match p.local_path_if_available().parent() {
if let Some(local_path) = p.local_path() { Some(p) => p.to_path_buf(),
match local_path.parent() { None => PathBuf::new(),
Some(p) => p.to_path_buf(), },
None => PathBuf::new(),
}
} else {
// Somehow we got the filename from the metadata of another crate, should never happen
PathBuf::new()
}
}
_ => PathBuf::new(), _ => PathBuf::new(),
}; };
// If user passed in `--playground-url` arg, we fill in crate name here // If user passed in `--playground-url` arg, we fill in crate name here

View file

@ -56,7 +56,11 @@ impl DocFolder for SourceCollector<'_, '_> {
Err(e) => { Err(e) => {
self.scx.tcx.sess.span_err( self.scx.tcx.sess.span_err(
item.span(self.scx.tcx).inner(), item.span(self.scx.tcx).inner(),
&format!("failed to render source code for `{}`: {}", filename, e), &format!(
"failed to render source code for `{}`: {}",
filename.prefer_local(),
e
),
); );
false false
} }
@ -80,7 +84,7 @@ impl SourceCollector<'_, 'tcx> {
if let Some(local_path) = file.local_path() { if let Some(local_path) = file.local_path() {
local_path.to_path_buf() local_path.to_path_buf()
} else { } else {
return Ok(()); unreachable!("only the current crate should have sources emitted");
} }
} }
_ => return Ok(()), _ => return Ok(()),
@ -119,7 +123,7 @@ impl SourceCollector<'_, 'tcx> {
href.push_str(&fname.to_string_lossy()); href.push_str(&fname.to_string_lossy());
let title = format!("{} - source", src_fname.to_string_lossy()); let title = format!("{} - source", src_fname.to_string_lossy());
let desc = format!("Source of the Rust file `{}`.", filename); let desc = format!("Source of the Rust file `{}`.", filename.prefer_remapped());
let page = layout::Page { let page = layout::Page {
title: &title, title: &title,
css_class: "source", css_class: "source",

View file

@ -119,7 +119,7 @@ impl<'a, 'b> CoverageCalculator<'a, 'b> {
&self &self
.items .items
.iter() .iter()
.map(|(k, v)| (k.to_string(), v)) .map(|(k, v)| (k.prefer_local().to_string(), v))
.collect::<BTreeMap<String, &ItemCount>>(), .collect::<BTreeMap<String, &ItemCount>>(),
) )
.expect("failed to convert JSON data to string") .expect("failed to convert JSON data to string")
@ -159,7 +159,7 @@ impl<'a, 'b> CoverageCalculator<'a, 'b> {
for (file, &count) in &self.items { for (file, &count) in &self.items {
if let Some(percentage) = count.percentage() { if let Some(percentage) = count.percentage() {
print_table_record( print_table_record(
&limit_filename_len(file.to_string()), &limit_filename_len(file.prefer_local().to_string_lossy().into()),
count, count,
percentage, percentage,
count.examples_percentage().unwrap_or(0.), count.examples_percentage().unwrap_or(0.),

View file

@ -47,7 +47,7 @@ pub struct MacroRefData {
impl MacroRefData { impl MacroRefData {
pub fn new(name: String, callee: Span, cx: &LateContext<'_>) -> Self { pub fn new(name: String, callee: Span, cx: &LateContext<'_>) -> Self {
let mut path = cx.sess().source_map().span_to_filename(callee).to_string(); let mut path = cx.sess().source_map().span_to_filename(callee).prefer_local().to_string();
// std lib paths are <::std::module::file type> // std lib paths are <::std::module::file type>
// so remove brackets, space and type. // so remove brackets, space and type.
@ -96,8 +96,7 @@ impl MacroUseImports {
let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_"); let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
if let Some(callee) = span.source_callee() { if let Some(callee) = span.source_callee() {
if !self.collected.contains(&call_site) { if !self.collected.contains(&call_site) {
self.mac_refs self.mac_refs.push(MacroRefData::new(name.to_string(), callee.def_site, cx));
.push(MacroRefData::new(name.to_string(), callee.def_site, cx));
self.collected.insert(call_site); self.collected.insert(call_site);
} }
} }
@ -175,7 +174,7 @@ impl<'tcx> LateLintPass<'tcx> for MacroUseImports {
.push((*item).to_string()); .push((*item).to_string());
check_dup.push((*item).to_string()); check_dup.push((*item).to_string());
} }
}, }
[root, rest @ ..] => { [root, rest @ ..] => {
if rest.iter().all(|item| !check_dup.contains(&(*item).to_string())) { if rest.iter().all(|item| !check_dup.contains(&(*item).to_string())) {
let filtered = rest let filtered = rest
@ -199,7 +198,7 @@ impl<'tcx> LateLintPass<'tcx> for MacroUseImports {
.push(rest.join("::")); .push(rest.join("::"));
check_dup.extend(rest.iter().map(ToString::to_string)); check_dup.extend(rest.iter().map(ToString::to_string));
} }
}, }
} }
} }
} }