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 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(

View File

@ -334,7 +334,9 @@ impl<'tcx> FunctionCx<'_, '_, 'tcx> {
let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
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.col_display as u32 + 1,
));

View File

@ -87,7 +87,7 @@ fn line_program_add_file(
filename => {
let dir_id = line_program.default_directory();
let dummy_file_name = LineString::new(
filename.to_string().into_bytes(),
filename.prefer_remapped().to_string().into_bytes(),
line_program.encoding(),
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 {
debug!("file_metadata: file_name: {}", source_file.name);
debug!("file_metadata: file_name: {:?}", source_file.name);
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() {
Some(cx.sess().working_dir.to_string_lossy(false).to_string())
} 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 caller = tcx.sess.source_map().lookup_char_pos(topmost.lo());
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.col_display as u32 + 1,
));

View File

@ -126,7 +126,8 @@ impl AnnotateSnippetEmitterWriter {
}
// owned: line source, line index, annotations
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
.into_iter()
.flat_map(|annotated_file| {

View File

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

View File

@ -468,7 +468,7 @@ impl 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_end: start.file.original_relative_byte_pos(span.hi()).0,
line_start: start.line,

View File

@ -1080,7 +1080,10 @@ impl<'a> ExtCtxt<'a> {
other => {
return Err(self.struct_span_err(
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
.into_local_path()
.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();
self.cx.root_path = dir_path.clone();

View File

@ -627,7 +627,7 @@ impl server::SourceFile for Rustc<'_> {
.to_str()
.expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
.to_string(),
_ => file.name.to_string(),
_ => file.name.prefer_local().to_string(),
}
}
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) {
(TypeError::Sorts(values), extra) => {
let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
(true, ty::Opaque(def_id, _)) => format!(
" (opaque type at {})",
self.tcx
(true, ty::Opaque(def_id, _)) => {
let pos = self
.tcx
.sess
.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)),
(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::Session;
use rustc_span::symbol::{Ident, Symbol};
use rustc_span::FileName;
use rustc_trait_selection::traits;
use rustc_typeck as typeck;
use tracing::{info, warn};
@ -575,14 +574,7 @@ fn write_out_deps(
.iter()
.filter(|fmap| fmap.is_real_file())
.filter(|fmap| !fmap.is_imported())
.map(|fmap| {
escape_dep_filename(&match &fmap.name {
FileName::Real(real) => {
real.local_path().unwrap_or(real.stable_name()).display().to_string()
}
_ => fmap.name.to_string(),
})
})
.map(|fmap| escape_dep_filename(&fmap.name.prefer_local().to_string()))
.collect();
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() {
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(())
})

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 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.col_display).unwrap().checked_add(1).unwrap(),
)

View File

@ -290,7 +290,7 @@ impl<'a, 'tcx> Instrumentor<'a, 'tcx> {
let tcx = self.tcx;
let source_map = tcx.sess.source_map();
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());
for covspan in coverage_spans {

View File

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

View File

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

View File

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

View File

@ -34,12 +34,7 @@ impl<'a> SpanUtils<'a> {
.to_string()
}
}
// If the file name was remapped, we assume the user
// 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(),
filename => filename.prefer_remapped().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 {
let mut hasher = StableHasher::new();
src.hash(&mut hasher);

View File

@ -369,11 +369,6 @@ impl SourceMap {
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.
pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
match file {
@ -420,7 +415,7 @@ impl SourceMap {
let hi = self.lookup_char_pos(sp.hi());
format!(
"{}:{}:{}: {}:{}",
lo.file.name,
lo.file.name.prefer_remapped(),
lo.line,
lo.col.to_usize() + 1,
hi.line,

View File

@ -93,7 +93,7 @@ impl ExternalCrate {
crate fn src_root(&self, tcx: TyCtxt<'_>) -> PathBuf {
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(),
None => PathBuf::new(),
},

View File

@ -840,7 +840,7 @@ impl Collector {
if !item_path.is_empty() {
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) {
@ -891,7 +891,7 @@ impl Tester for Collector {
local_path.to_path_buf()
} else {
// 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"),
@ -899,7 +899,8 @@ impl Tester for Collector {
// For example `module/file.rs` would become `module_file_rs`
let file = filename
.to_string()
.prefer_local()
.to_string_lossy()
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect::<String>();

View File

@ -376,17 +376,10 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
} = options;
let src_root = match krate.src {
FileName::Real(ref p) => {
if let Some(local_path) = p.local_path() {
match local_path.parent() {
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()
}
}
FileName::Real(ref p) => match p.local_path_if_available().parent() {
Some(p) => p.to_path_buf(),
None => PathBuf::new(),
},
_ => PathBuf::new(),
};
// 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) => {
self.scx.tcx.sess.span_err(
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
}
@ -80,7 +84,7 @@ impl SourceCollector<'_, 'tcx> {
if let Some(local_path) = file.local_path() {
local_path.to_path_buf()
} else {
return Ok(());
unreachable!("only the current crate should have sources emitted");
}
}
_ => return Ok(()),
@ -119,7 +123,7 @@ impl SourceCollector<'_, 'tcx> {
href.push_str(&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 {
title: &title,
css_class: "source",

View File

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

View File

@ -47,7 +47,7 @@ pub struct MacroRefData {
impl MacroRefData {
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>
// 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, '!'), "_");
if let Some(callee) = span.source_callee() {
if !self.collected.contains(&call_site) {
self.mac_refs
.push(MacroRefData::new(name.to_string(), callee.def_site, cx));
self.mac_refs.push(MacroRefData::new(name.to_string(), callee.def_site, cx));
self.collected.insert(call_site);
}
}
@ -175,7 +174,7 @@ impl<'tcx> LateLintPass<'tcx> for MacroUseImports {
.push((*item).to_string());
check_dup.push((*item).to_string());
}
},
}
[root, rest @ ..] => {
if rest.iter().all(|item| !check_dup.contains(&(*item).to_string())) {
let filtered = rest
@ -199,7 +198,7 @@ impl<'tcx> LateLintPass<'tcx> for MacroUseImports {
.push(rest.join("::"));
check_dup.extend(rest.iter().map(ToString::to_string));
}
},
}
}
}
}