Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use PathBuf instead of String where applicable #46335

Merged
merged 1 commit into from
Dec 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions src/libproc_macro/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ use syntax::parse::{self, token};
use syntax::symbol::Symbol;
use syntax::tokenstream;
use syntax_pos::DUMMY_SP;
use syntax_pos::{FileMap, Pos, SyntaxContext};
use syntax_pos::{FileMap, Pos, SyntaxContext, FileName};
use syntax_pos::hygiene::Mark;

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

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

Expand All @@ -306,17 +306,17 @@ impl SourceFile {
}

#[unstable(feature = "proc_macro", issue = "38356")]
impl AsRef<str> for SourceFile {
fn as_ref(&self) -> &str {
self.as_str()
impl AsRef<FileName> for SourceFile {
fn as_ref(&self) -> &FileName {
self.path()
}
}

#[unstable(feature = "proc_macro", issue = "38356")]
impl fmt::Debug for SourceFile {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("SourceFile")
.field("path", &self.as_str())
.field("path", self.path())
.field("is_real", &self.is_real())
.finish()
}
Expand All @@ -333,8 +333,8 @@ impl PartialEq for SourceFile {
impl Eq for SourceFile {}

#[unstable(feature = "proc_macro", issue = "38356")]
impl PartialEq<str> for SourceFile {
fn eq(&self, other: &str) -> bool {
impl PartialEq<FileName> for SourceFile {
fn eq(&self, other: &FileName) -> bool {
self.as_ref() == other
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/librustc/hir/print.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use syntax::print::pprust::PrintState;
use syntax::ptr::P;
use syntax::symbol::keywords;
use syntax::util::parser::{self, AssocOp, Fixity};
use syntax_pos::{self, BytePos};
use syntax_pos::{self, BytePos, FileName};

use hir;
use hir::{PatKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier, RangeEnd};
Expand Down Expand Up @@ -125,7 +125,7 @@ pub const default_columns: usize = 78;
pub fn print_crate<'a>(cm: &'a CodeMap,
sess: &ParseSess,
krate: &hir::Crate,
filename: String,
filename: FileName,
input: &mut Read,
out: Box<Write + 'a>,
ann: &'a PpAnn,
Expand All @@ -144,7 +144,7 @@ pub fn print_crate<'a>(cm: &'a CodeMap,
impl<'a> State<'a> {
pub fn new_from_input(cm: &'a CodeMap,
sess: &ParseSess,
filename: String,
filename: FileName,
input: &mut Read,
out: Box<Write + 'a>,
ann: &'a PpAnn,
Expand Down
11 changes: 11 additions & 0 deletions src/librustc/ich/impls_syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,17 @@ impl_stable_hash_for!(enum ::syntax_pos::hygiene::CompilerDesugaringKind {
QuestionMark
});

impl_stable_hash_for!(enum ::syntax_pos::FileName {
Real(pb),
Macros(s),
QuoteExpansion,
Anon,
MacroExpansion,
ProcMacroSourceCode,
CfgSpec,
Custom(s)
});

impl<'gcx> HashStable<StableHashingContext<'gcx>> for FileMap {
fn hash_stable<W: StableHasherResult>(&self,
hcx: &mut StableHashingContext<'gcx>,
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/stability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
let span_key = msp.primary_span().and_then(|sp: Span|
if sp != DUMMY_SP {
let file = cm.lookup_char_pos(sp.lo()).file;
if file.name.starts_with("<") && file.name.ends_with(" macros>") {
if file.name.is_macros() {
None
} else {
Some(span)
Expand Down
37 changes: 28 additions & 9 deletions src/librustc/session/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use lint;
use middle::cstore;

use syntax::ast::{self, IntTy, UintTy};
use syntax::codemap::FilePathMapping;
use syntax::codemap::{FilePathMapping, FileName};
use syntax::parse::token;
use syntax::parse;
use syntax::symbol::Symbol;
Expand Down Expand Up @@ -440,7 +440,7 @@ pub enum Input {
File(PathBuf),
Str {
/// String that is shown in place of a filename
name: String,
name: FileName,
/// Anonymous source string
input: String,
},
Expand Down Expand Up @@ -733,7 +733,9 @@ macro_rules! options {
Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
pub const parse_string: Option<&'static str> = Some("a string");
pub const parse_string_push: Option<&'static str> = Some("a string");
pub const parse_pathbuf_push: Option<&'static str> = Some("a path");
pub const parse_opt_string: Option<&'static str> = Some("a string");
pub const parse_opt_pathbuf: Option<&'static str> = Some("a path");
pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
pub const parse_uint: Option<&'static str> = Some("a number");
Expand All @@ -757,6 +759,7 @@ macro_rules! options {
mod $mod_set {
use super::{$struct_name, Passes, SomePasses, AllPasses, Sanitizer};
use rustc_back::{LinkerFlavor, PanicStrategy, RelroLevel};
use std::path::PathBuf;

$(
pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
Expand Down Expand Up @@ -797,6 +800,13 @@ macro_rules! options {
}
}

fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
match v {
Some(s) => { *slot = Some(PathBuf::from(s)); true },
None => false,
}
}

fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
match v {
Some(s) => { *slot = s.to_string(); true },
Expand All @@ -811,6 +821,13 @@ macro_rules! options {
}
}

fn parse_pathbuf_push(slot: &mut Vec<PathBuf>, v: Option<&str>) -> bool {
match v {
Some(s) => { slot.push(PathBuf::from(s)); true },
None => false,
}
}

fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
-> bool {
match v {
Expand Down Expand Up @@ -931,7 +948,7 @@ options! {CodegenOptions, CodegenSetter, basic_codegen_options,
CG_OPTIONS, cg_type_desc, cgsetters,
ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
"this option is deprecated and does nothing"),
linker: Option<String> = (None, parse_opt_string, [UNTRACKED],
linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
"system linker to link outputs with"),
link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
"a single extra argument to append to the linker invocation (can be used several times)"),
Expand Down Expand Up @@ -1151,9 +1168,9 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
"set the optimization fuel quota for a crate"),
print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
"make Rustc print the total optimization fuel used by a crate"),
remap_path_prefix_from: Vec<String> = (vec![], parse_string_push, [TRACKED],
remap_path_prefix_from: Vec<PathBuf> = (vec![], parse_pathbuf_push, [TRACKED],
"add a source pattern to the file path remapping config"),
remap_path_prefix_to: Vec<String> = (vec![], parse_string_push, [TRACKED],
remap_path_prefix_to: Vec<PathBuf> = (vec![], parse_pathbuf_push, [TRACKED],
"add a mapping target to the file path remapping config"),
force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
"force all crates to be `rustc_private` unstable"),
Expand Down Expand Up @@ -1472,7 +1489,7 @@ pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
cfgspecs.into_iter().map(|s| {
let sess = parse::ParseSess::new(FilePathMapping::empty());
let mut parser =
parse::new_parser_from_source_str(&sess, "cfgspec".to_string(), s.to_string());
parse::new_parser_from_source_str(&sess, FileName::CfgSpec, s.to_string());

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

Expand Down Expand Up @@ -1594,13 +1611,13 @@ pub fn build_session_options_and_crate_config(matches: &getopts::Matches)
for source in &debugging_opts.remap_path_prefix_from[remap_path_prefix_targets..] {
early_error(error_format,
&format!("option `-Zremap-path-prefix-from='{}'` does not have \
a corresponding `-Zremap-path-prefix-to`", source))
a corresponding `-Zremap-path-prefix-to`", source.display()))
}
} else if remap_path_prefix_targets > remap_path_prefix_sources {
for target in &debugging_opts.remap_path_prefix_to[remap_path_prefix_sources..] {
early_error(error_format,
&format!("option `-Zremap-path-prefix-to='{}'` does not have \
a corresponding `-Zremap-path-prefix-from`", target))
a corresponding `-Zremap-path-prefix-from`", target.display()))
}
}

Expand Down Expand Up @@ -2001,6 +2018,7 @@ mod dep_tracking {
impl_dep_tracking_hash_via_hash!(usize);
impl_dep_tracking_hash_via_hash!(u64);
impl_dep_tracking_hash_via_hash!(String);
impl_dep_tracking_hash_via_hash!(PathBuf);
impl_dep_tracking_hash_via_hash!(lint::Level);
impl_dep_tracking_hash_via_hash!(Option<bool>);
impl_dep_tracking_hash_via_hash!(Option<usize>);
Expand All @@ -2025,6 +2043,7 @@ mod dep_tracking {
impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);

impl_dep_tracking_hash_for_sortable_vec_of!(String);
impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
impl_dep_tracking_hash_for_sortable_vec_of!((String, Option<String>,
Expand Down Expand Up @@ -2533,7 +2552,7 @@ mod tests {
opts.cg.ar = Some(String::from("abc"));
assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

opts.cg.linker = Some(String::from("linker"));
opts.cg.linker = Some(PathBuf::from("linker"));
assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
Expand Down
8 changes: 4 additions & 4 deletions src/librustc/session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,10 @@ pub struct Session {
pub default_sysroot: Option<PathBuf>,
/// The name of the root source file of the crate, in the local file system.
/// `None` means that there is no source file.
pub local_crate_source_file: Option<String>,
pub local_crate_source_file: Option<PathBuf>,
/// The directory the compiler has been executed in plus a flag indicating
/// if the value stored here has been affected by path remapping.
pub working_dir: (String, bool),
pub working_dir: (PathBuf, bool),
pub lint_store: RefCell<lint::LintStore>,
pub buffered_lints: RefCell<Option<lint::LintBuffer>>,
/// Set of (DiagnosticId, Option<Span>, message) tuples tracking
Expand Down Expand Up @@ -864,7 +864,7 @@ pub fn build_session_(sopts: config::Options,
let file_path_mapping = sopts.file_path_mapping();

let local_crate_source_file = local_crate_source_file.map(|path| {
file_path_mapping.map_prefix(path.to_string_lossy().into_owned()).0
file_path_mapping.map_prefix(path).0
});

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

let working_dir = match env::current_dir() {
Ok(dir) => dir.to_string_lossy().into_owned(),
Ok(dir) => dir,
Err(e) => {
panic!(p_s.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)))
}
Expand Down
21 changes: 8 additions & 13 deletions src/librustc_driver/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ use syntax::ext::base::ExtCtxt;
use syntax::fold::Folder;
use syntax::parse::{self, PResult};
use syntax::util::node_count::NodeCounter;
use syntax_pos::FileName;
use syntax;
use syntax_ext;
use arena::DroplessArena;
Expand Down Expand Up @@ -306,17 +307,9 @@ fn keep_hygiene_data(sess: &Session) -> bool {
sess.opts.debugging_opts.keep_hygiene_data
}


/// The name used for source code that doesn't originate in a file
/// (e.g. source from stdin or a string)
pub fn anon_src() -> String {
"<anon>".to_string()
}

pub fn source_name(input: &Input) -> String {
pub fn source_name(input: &Input) -> FileName {
match *input {
// FIXME (#9639): This needs to handle non-utf8 paths
Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
Input::File(ref ifile) => ifile.clone().into(),
Input::Str { ref name, .. } => name.clone(),
}
}
Expand Down Expand Up @@ -573,7 +566,9 @@ pub fn phase_1_parse_input<'a>(control: &CompileController,
parse::parse_crate_from_file(file, &sess.parse_sess)
}
Input::Str { ref input, ref name } => {
parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
parse::parse_crate_from_source_str(name.clone(),
input.clone(),
&sess.parse_sess)
}
}
})?;
Expand Down Expand Up @@ -1135,10 +1130,10 @@ pub fn phase_5_run_llvm_passes<Trans: TransCrate>(sess: &Session,
(sess.compile_status(), trans)
}

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

fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {
Expand Down
8 changes: 5 additions & 3 deletions src/librustc_driver/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ use syntax::ast;
use syntax::codemap::{CodeMap, FileLoader, RealFileLoader};
use syntax::feature_gate::{GatedCfg, UnstableFeatures};
use syntax::parse::{self, PResult};
use syntax_pos::{DUMMY_SP, MultiSpan};
use syntax_pos::{DUMMY_SP, MultiSpan, FileName};

#[cfg(test)]
mod test;
Expand Down Expand Up @@ -274,7 +274,7 @@ fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
if ifile == "-" {
let mut src = String::new();
io::stdin().read_to_string(&mut src).unwrap();
Some((Input::Str { name: driver::anon_src(), input: src },
Some((Input::Str { name: FileName::Anon, input: src },
None))
} else {
Some((Input::File(PathBuf::from(ifile)),
Expand Down Expand Up @@ -1165,7 +1165,9 @@ fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<as
parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
}
Input::Str { ref name, ref input } => {
parse::parse_crate_attrs_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
parse::parse_crate_attrs_from_source_str(name.clone(),
input.clone(),
&sess.parse_sess)
}
}
}
Expand Down
Loading