Skip to content

Commit d732da8

Browse files
committed
Use PathBuf instead of String where applicable
1 parent 8954b16 commit d732da8

File tree

48 files changed

+444
-309
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+444
-309
lines changed

src/libproc_macro/lib.rs

+10-10
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ use syntax::parse::{self, token};
5959
use syntax::symbol::Symbol;
6060
use syntax::tokenstream;
6161
use syntax_pos::DUMMY_SP;
62-
use syntax_pos::{FileMap, Pos, SyntaxContext};
62+
use syntax_pos::{FileMap, Pos, SyntaxContext, FileName};
6363
use syntax_pos::hygiene::Mark;
6464

6565
/// The main type provided by this crate, representing an abstract stream of
@@ -89,7 +89,7 @@ impl FromStr for TokenStream {
8989
fn from_str(src: &str) -> Result<TokenStream, LexError> {
9090
__internal::with_sess(|(sess, mark)| {
9191
let src = src.to_string();
92-
let name = "<proc-macro source code>".to_string();
92+
let name = FileName::ProcMacroSourceCode;
9393
let expn_info = mark.expn_info().unwrap();
9494
let call_site = expn_info.call_site;
9595
// notify the expansion info that it is unhygienic
@@ -279,7 +279,7 @@ pub struct SourceFile {
279279
}
280280

281281
impl SourceFile {
282-
/// Get the path to this source file as a string.
282+
/// Get the path to this source file.
283283
///
284284
/// ### Note
285285
/// If the code span associated with this `SourceFile` was generated by an external macro, this
@@ -290,7 +290,7 @@ impl SourceFile {
290290
///
291291
/// [`is_real`]: #method.is_real
292292
# [unstable(feature = "proc_macro", issue = "38356")]
293-
pub fn as_str(&self) -> &str {
293+
pub fn path(&self) -> &FileName {
294294
&self.filemap.name
295295
}
296296

@@ -306,17 +306,17 @@ impl SourceFile {
306306
}
307307

308308
#[unstable(feature = "proc_macro", issue = "38356")]
309-
impl AsRef<str> for SourceFile {
310-
fn as_ref(&self) -> &str {
311-
self.as_str()
309+
impl AsRef<FileName> for SourceFile {
310+
fn as_ref(&self) -> &FileName {
311+
self.path()
312312
}
313313
}
314314

315315
#[unstable(feature = "proc_macro", issue = "38356")]
316316
impl fmt::Debug for SourceFile {
317317
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
318318
f.debug_struct("SourceFile")
319-
.field("path", &self.as_str())
319+
.field("path", self.path())
320320
.field("is_real", &self.is_real())
321321
.finish()
322322
}
@@ -333,8 +333,8 @@ impl PartialEq for SourceFile {
333333
impl Eq for SourceFile {}
334334

335335
#[unstable(feature = "proc_macro", issue = "38356")]
336-
impl PartialEq<str> for SourceFile {
337-
fn eq(&self, other: &str) -> bool {
336+
impl PartialEq<FileName> for SourceFile {
337+
fn eq(&self, other: &FileName) -> bool {
338338
self.as_ref() == other
339339
}
340340
}

src/librustc/hir/print.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use syntax::print::pprust::PrintState;
2121
use syntax::ptr::P;
2222
use syntax::symbol::keywords;
2323
use syntax::util::parser::{self, AssocOp, Fixity};
24-
use syntax_pos::{self, BytePos};
24+
use syntax_pos::{self, BytePos, FileName};
2525

2626
use hir;
2727
use hir::{PatKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier, RangeEnd};
@@ -125,7 +125,7 @@ pub const default_columns: usize = 78;
125125
pub fn print_crate<'a>(cm: &'a CodeMap,
126126
sess: &ParseSess,
127127
krate: &hir::Crate,
128-
filename: String,
128+
filename: FileName,
129129
input: &mut Read,
130130
out: Box<Write + 'a>,
131131
ann: &'a PpAnn,
@@ -144,7 +144,7 @@ pub fn print_crate<'a>(cm: &'a CodeMap,
144144
impl<'a> State<'a> {
145145
pub fn new_from_input(cm: &'a CodeMap,
146146
sess: &ParseSess,
147-
filename: String,
147+
filename: FileName,
148148
input: &mut Read,
149149
out: Box<Write + 'a>,
150150
ann: &'a PpAnn,

src/librustc/ich/impls_syntax.rs

+11
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,17 @@ impl_stable_hash_for!(enum ::syntax_pos::hygiene::CompilerDesugaringKind {
371371
QuestionMark
372372
});
373373

374+
impl_stable_hash_for!(enum ::syntax_pos::FileName {
375+
Real(pb),
376+
Macros(s),
377+
QuoteExpansion,
378+
Anon,
379+
MacroExpansion,
380+
ProcMacroSourceCode,
381+
CfgSpec,
382+
Custom(s)
383+
});
384+
374385
impl<'gcx> HashStable<StableHashingContext<'gcx>> for FileMap {
375386
fn hash_stable<W: StableHasherResult>(&self,
376387
hcx: &mut StableHashingContext<'gcx>,

src/librustc/middle/stability.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -607,7 +607,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
607607
let span_key = msp.primary_span().and_then(|sp: Span|
608608
if sp != DUMMY_SP {
609609
let file = cm.lookup_char_pos(sp.lo()).file;
610-
if file.name.starts_with("<") && file.name.ends_with(" macros>") {
610+
if file.name.is_macros() {
611611
None
612612
} else {
613613
Some(span)

src/librustc/session/config.rs

+28-9
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ use lint;
2727
use middle::cstore;
2828

2929
use syntax::ast::{self, IntTy, UintTy};
30-
use syntax::codemap::FilePathMapping;
30+
use syntax::codemap::{FilePathMapping, FileName};
3131
use syntax::parse::token;
3232
use syntax::parse;
3333
use syntax::symbol::Symbol;
@@ -440,7 +440,7 @@ pub enum Input {
440440
File(PathBuf),
441441
Str {
442442
/// String that is shown in place of a filename
443-
name: String,
443+
name: FileName,
444444
/// Anonymous source string
445445
input: String,
446446
},
@@ -733,7 +733,9 @@ macro_rules! options {
733733
Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
734734
pub const parse_string: Option<&'static str> = Some("a string");
735735
pub const parse_string_push: Option<&'static str> = Some("a string");
736+
pub const parse_pathbuf_push: Option<&'static str> = Some("a path");
736737
pub const parse_opt_string: Option<&'static str> = Some("a string");
738+
pub const parse_opt_pathbuf: Option<&'static str> = Some("a path");
737739
pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
738740
pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
739741
pub const parse_uint: Option<&'static str> = Some("a number");
@@ -757,6 +759,7 @@ macro_rules! options {
757759
mod $mod_set {
758760
use super::{$struct_name, Passes, SomePasses, AllPasses, Sanitizer};
759761
use rustc_back::{LinkerFlavor, PanicStrategy, RelroLevel};
762+
use std::path::PathBuf;
760763

761764
$(
762765
pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
@@ -797,6 +800,13 @@ macro_rules! options {
797800
}
798801
}
799802

803+
fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
804+
match v {
805+
Some(s) => { *slot = Some(PathBuf::from(s)); true },
806+
None => false,
807+
}
808+
}
809+
800810
fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
801811
match v {
802812
Some(s) => { *slot = s.to_string(); true },
@@ -811,6 +821,13 @@ macro_rules! options {
811821
}
812822
}
813823

824+
fn parse_pathbuf_push(slot: &mut Vec<PathBuf>, v: Option<&str>) -> bool {
825+
match v {
826+
Some(s) => { slot.push(PathBuf::from(s)); true },
827+
None => false,
828+
}
829+
}
830+
814831
fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
815832
-> bool {
816833
match v {
@@ -931,7 +948,7 @@ options! {CodegenOptions, CodegenSetter, basic_codegen_options,
931948
CG_OPTIONS, cg_type_desc, cgsetters,
932949
ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
933950
"this option is deprecated and does nothing"),
934-
linker: Option<String> = (None, parse_opt_string, [UNTRACKED],
951+
linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
935952
"system linker to link outputs with"),
936953
link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
937954
"a single extra argument to append to the linker invocation (can be used several times)"),
@@ -1151,9 +1168,9 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
11511168
"set the optimization fuel quota for a crate"),
11521169
print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
11531170
"make Rustc print the total optimization fuel used by a crate"),
1154-
remap_path_prefix_from: Vec<String> = (vec![], parse_string_push, [TRACKED],
1171+
remap_path_prefix_from: Vec<PathBuf> = (vec![], parse_pathbuf_push, [TRACKED],
11551172
"add a source pattern to the file path remapping config"),
1156-
remap_path_prefix_to: Vec<String> = (vec![], parse_string_push, [TRACKED],
1173+
remap_path_prefix_to: Vec<PathBuf> = (vec![], parse_pathbuf_push, [TRACKED],
11571174
"add a mapping target to the file path remapping config"),
11581175
force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
11591176
"force all crates to be `rustc_private` unstable"),
@@ -1472,7 +1489,7 @@ pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
14721489
cfgspecs.into_iter().map(|s| {
14731490
let sess = parse::ParseSess::new(FilePathMapping::empty());
14741491
let mut parser =
1475-
parse::new_parser_from_source_str(&sess, "cfgspec".to_string(), s.to_string());
1492+
parse::new_parser_from_source_str(&sess, FileName::CfgSpec, s.to_string());
14761493

14771494
let meta_item = panictry!(parser.parse_meta_item());
14781495

@@ -1594,13 +1611,13 @@ pub fn build_session_options_and_crate_config(matches: &getopts::Matches)
15941611
for source in &debugging_opts.remap_path_prefix_from[remap_path_prefix_targets..] {
15951612
early_error(error_format,
15961613
&format!("option `-Zremap-path-prefix-from='{}'` does not have \
1597-
a corresponding `-Zremap-path-prefix-to`", source))
1614+
a corresponding `-Zremap-path-prefix-to`", source.display()))
15981615
}
15991616
} else if remap_path_prefix_targets > remap_path_prefix_sources {
16001617
for target in &debugging_opts.remap_path_prefix_to[remap_path_prefix_sources..] {
16011618
early_error(error_format,
16021619
&format!("option `-Zremap-path-prefix-to='{}'` does not have \
1603-
a corresponding `-Zremap-path-prefix-from`", target))
1620+
a corresponding `-Zremap-path-prefix-from`", target.display()))
16041621
}
16051622
}
16061623

@@ -2001,6 +2018,7 @@ mod dep_tracking {
20012018
impl_dep_tracking_hash_via_hash!(usize);
20022019
impl_dep_tracking_hash_via_hash!(u64);
20032020
impl_dep_tracking_hash_via_hash!(String);
2021+
impl_dep_tracking_hash_via_hash!(PathBuf);
20042022
impl_dep_tracking_hash_via_hash!(lint::Level);
20052023
impl_dep_tracking_hash_via_hash!(Option<bool>);
20062024
impl_dep_tracking_hash_via_hash!(Option<usize>);
@@ -2025,6 +2043,7 @@ mod dep_tracking {
20252043
impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
20262044

20272045
impl_dep_tracking_hash_for_sortable_vec_of!(String);
2046+
impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
20282047
impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
20292048
impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
20302049
impl_dep_tracking_hash_for_sortable_vec_of!((String, Option<String>,
@@ -2533,7 +2552,7 @@ mod tests {
25332552
opts.cg.ar = Some(String::from("abc"));
25342553
assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
25352554

2536-
opts.cg.linker = Some(String::from("linker"));
2555+
opts.cg.linker = Some(PathBuf::from("linker"));
25372556
assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
25382557

25392558
opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);

src/librustc/session/mod.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,10 @@ pub struct Session {
6969
pub default_sysroot: Option<PathBuf>,
7070
/// The name of the root source file of the crate, in the local file system.
7171
/// `None` means that there is no source file.
72-
pub local_crate_source_file: Option<String>,
72+
pub local_crate_source_file: Option<PathBuf>,
7373
/// The directory the compiler has been executed in plus a flag indicating
7474
/// if the value stored here has been affected by path remapping.
75-
pub working_dir: (String, bool),
75+
pub working_dir: (PathBuf, bool),
7676
pub lint_store: RefCell<lint::LintStore>,
7777
pub buffered_lints: RefCell<Option<lint::LintBuffer>>,
7878
/// Set of (DiagnosticId, Option<Span>, message) tuples tracking
@@ -864,7 +864,7 @@ pub fn build_session_(sopts: config::Options,
864864
let file_path_mapping = sopts.file_path_mapping();
865865

866866
let local_crate_source_file = local_crate_source_file.map(|path| {
867-
file_path_mapping.map_prefix(path.to_string_lossy().into_owned()).0
867+
file_path_mapping.map_prefix(path).0
868868
});
869869

870870
let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
@@ -874,7 +874,7 @@ pub fn build_session_(sopts: config::Options,
874874
let print_fuel = Cell::new(0);
875875

876876
let working_dir = match env::current_dir() {
877-
Ok(dir) => dir.to_string_lossy().into_owned(),
877+
Ok(dir) => dir,
878878
Err(e) => {
879879
panic!(p_s.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)))
880880
}

src/librustc_driver/driver.rs

+8-13
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ use syntax::ext::base::ExtCtxt;
5959
use syntax::fold::Folder;
6060
use syntax::parse::{self, PResult};
6161
use syntax::util::node_count::NodeCounter;
62+
use syntax_pos::FileName;
6263
use syntax;
6364
use syntax_ext;
6465
use arena::DroplessArena;
@@ -306,17 +307,9 @@ fn keep_hygiene_data(sess: &Session) -> bool {
306307
sess.opts.debugging_opts.keep_hygiene_data
307308
}
308309

309-
310-
/// The name used for source code that doesn't originate in a file
311-
/// (e.g. source from stdin or a string)
312-
pub fn anon_src() -> String {
313-
"<anon>".to_string()
314-
}
315-
316-
pub fn source_name(input: &Input) -> String {
310+
pub fn source_name(input: &Input) -> FileName {
317311
match *input {
318-
// FIXME (#9639): This needs to handle non-utf8 paths
319-
Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
312+
Input::File(ref ifile) => ifile.clone().into(),
320313
Input::Str { ref name, .. } => name.clone(),
321314
}
322315
}
@@ -573,7 +566,9 @@ pub fn phase_1_parse_input<'a>(control: &CompileController,
573566
parse::parse_crate_from_file(file, &sess.parse_sess)
574567
}
575568
Input::Str { ref input, ref name } => {
576-
parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
569+
parse::parse_crate_from_source_str(name.clone(),
570+
input.clone(),
571+
&sess.parse_sess)
577572
}
578573
}
579574
})?;
@@ -1135,10 +1130,10 @@ pub fn phase_5_run_llvm_passes<Trans: TransCrate>(sess: &Session,
11351130
(sess.compile_status(), trans)
11361131
}
11371132

1138-
fn escape_dep_filename(filename: &str) -> String {
1133+
fn escape_dep_filename(filename: &FileName) -> String {
11391134
// Apparently clang and gcc *only* escape spaces:
11401135
// http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1141-
filename.replace(" ", "\\ ")
1136+
filename.to_string().replace(" ", "\\ ")
11421137
}
11431138

11441139
fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {

src/librustc_driver/lib.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ use syntax::ast;
9898
use syntax::codemap::{CodeMap, FileLoader, RealFileLoader};
9999
use syntax::feature_gate::{GatedCfg, UnstableFeatures};
100100
use syntax::parse::{self, PResult};
101-
use syntax_pos::{DUMMY_SP, MultiSpan};
101+
use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
102102

103103
#[cfg(test)]
104104
mod test;
@@ -274,7 +274,7 @@ fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
274274
if ifile == "-" {
275275
let mut src = String::new();
276276
io::stdin().read_to_string(&mut src).unwrap();
277-
Some((Input::Str { name: driver::anon_src(), input: src },
277+
Some((Input::Str { name: FileName::Anon, input: src },
278278
None))
279279
} else {
280280
Some((Input::File(PathBuf::from(ifile)),
@@ -1165,7 +1165,9 @@ fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<as
11651165
parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
11661166
}
11671167
Input::Str { ref name, ref input } => {
1168-
parse::parse_crate_attrs_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
1168+
parse::parse_crate_attrs_from_source_str(name.clone(),
1169+
input.clone(),
1170+
&sess.parse_sess)
11691171
}
11701172
}
11711173
}

0 commit comments

Comments
 (0)