Introduce SearchPath and replace SearchPaths with Vec<SearchPath>.

It's more idiomatic, makes the code shorter, and will help with the next
commit.
This commit is contained in:
Nicholas Nethercote
2018-11-22 16:33:07 +11:00
parent 2640da7d13
commit f13006182c
7 changed files with 81 additions and 96 deletions

View File

@@ -14,7 +14,7 @@
use std::str::FromStr; use std::str::FromStr;
use session::{early_error, early_warn, Session}; use session::{early_error, early_warn, Session};
use session::search_paths::SearchPaths; use session::search_paths::SearchPath;
use rustc_target::spec::{LinkerFlavor, PanicStrategy, RelroLevel}; use rustc_target::spec::{LinkerFlavor, PanicStrategy, RelroLevel};
use rustc_target::spec::{Target, TargetTriple}; use rustc_target::spec::{Target, TargetTriple};
@@ -374,7 +374,7 @@ top_level_options!(
lint_cap: Option<lint::Level> [TRACKED], lint_cap: Option<lint::Level> [TRACKED],
describe_lints: bool [UNTRACKED], describe_lints: bool [UNTRACKED],
output_types: OutputTypes [TRACKED], output_types: OutputTypes [TRACKED],
search_paths: SearchPaths [UNTRACKED], search_paths: Vec<SearchPath> [UNTRACKED],
libs: Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> [TRACKED], libs: Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> [TRACKED],
maybe_sysroot: Option<PathBuf> [TRACKED], maybe_sysroot: Option<PathBuf> [TRACKED],
@@ -593,7 +593,7 @@ impl Default for Options {
lint_cap: None, lint_cap: None,
describe_lints: false, describe_lints: false,
output_types: OutputTypes(BTreeMap::new()), output_types: OutputTypes(BTreeMap::new()),
search_paths: SearchPaths::new(), search_paths: vec![],
maybe_sysroot: None, maybe_sysroot: None,
target_triple: TargetTriple::from_triple(host_triple()), target_triple: TargetTriple::from_triple(host_triple()),
test: false, test: false,
@@ -2115,9 +2115,9 @@ pub fn build_session_options_and_crate_config(
} }
}; };
let mut search_paths = SearchPaths::new(); let mut search_paths = vec![];
for s in &matches.opt_strs("L") { for s in &matches.opt_strs("L") {
search_paths.add_path(&s[..], error_format); search_paths.push(SearchPath::from_cli_opt(&s[..], error_format));
} }
let libs = matches let libs = matches
@@ -2535,6 +2535,7 @@ mod tests {
use session::config::{build_configuration, build_session_options_and_crate_config}; use session::config::{build_configuration, build_session_options_and_crate_config};
use session::config::{LtoCli, CrossLangLto}; use session::config::{LtoCli, CrossLangLto};
use session::build_session; use session::build_session;
use session::search_paths::SearchPath;
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
use std::iter::FromIterator; use std::iter::FromIterator;
use std::path::PathBuf; use std::path::PathBuf;
@@ -2790,48 +2791,48 @@ mod tests {
// Reference // Reference
v1.search_paths v1.search_paths
.add_path("native=abc", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("native=abc", super::ErrorOutputType::Json(false)));
v1.search_paths v1.search_paths
.add_path("crate=def", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("crate=def", super::ErrorOutputType::Json(false)));
v1.search_paths v1.search_paths
.add_path("dependency=ghi", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("dependency=ghi", super::ErrorOutputType::Json(false)));
v1.search_paths v1.search_paths
.add_path("framework=jkl", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("framework=jkl", super::ErrorOutputType::Json(false)));
v1.search_paths v1.search_paths
.add_path("all=mno", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("all=mno", super::ErrorOutputType::Json(false)));
v2.search_paths v2.search_paths
.add_path("native=abc", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("native=abc", super::ErrorOutputType::Json(false)));
v2.search_paths v2.search_paths
.add_path("dependency=ghi", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("dependency=ghi", super::ErrorOutputType::Json(false)));
v2.search_paths v2.search_paths
.add_path("crate=def", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("crate=def", super::ErrorOutputType::Json(false)));
v2.search_paths v2.search_paths
.add_path("framework=jkl", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("framework=jkl", super::ErrorOutputType::Json(false)));
v2.search_paths v2.search_paths
.add_path("all=mno", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("all=mno", super::ErrorOutputType::Json(false)));
v3.search_paths v3.search_paths
.add_path("crate=def", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("crate=def", super::ErrorOutputType::Json(false)));
v3.search_paths v3.search_paths
.add_path("framework=jkl", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("framework=jkl", super::ErrorOutputType::Json(false)));
v3.search_paths v3.search_paths
.add_path("native=abc", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("native=abc", super::ErrorOutputType::Json(false)));
v3.search_paths v3.search_paths
.add_path("dependency=ghi", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("dependency=ghi", super::ErrorOutputType::Json(false)));
v3.search_paths v3.search_paths
.add_path("all=mno", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("all=mno", super::ErrorOutputType::Json(false)));
v4.search_paths v4.search_paths
.add_path("all=mno", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("all=mno", super::ErrorOutputType::Json(false)));
v4.search_paths v4.search_paths
.add_path("native=abc", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("native=abc", super::ErrorOutputType::Json(false)));
v4.search_paths v4.search_paths
.add_path("crate=def", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("crate=def", super::ErrorOutputType::Json(false)));
v4.search_paths v4.search_paths
.add_path("dependency=ghi", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("dependency=ghi", super::ErrorOutputType::Json(false)));
v4.search_paths v4.search_paths
.add_path("framework=jkl", super::ErrorOutputType::Json(false)); .push(SearchPath::from_cli_opt("framework=jkl", super::ErrorOutputType::Json(false)));
assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash()); assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash()); assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());

View File

@@ -18,7 +18,7 @@ use std::env;
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use session::search_paths::{SearchPaths, PathKind}; use session::search_paths::{SearchPath, PathKind};
use rustc_fs_util::fix_windows_verbatim_for_gcc; use rustc_fs_util::fix_windows_verbatim_for_gcc;
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
@@ -31,27 +31,28 @@ pub enum FileMatch {
pub struct FileSearch<'a> { pub struct FileSearch<'a> {
pub sysroot: &'a Path, pub sysroot: &'a Path,
pub search_paths: &'a SearchPaths, pub search_paths: &'a [SearchPath],
pub triple: &'a str, pub triple: &'a str,
pub kind: PathKind, pub kind: PathKind,
} }
impl<'a> FileSearch<'a> { impl<'a> FileSearch<'a> {
pub fn for_each_lib_search_path<F>(&self, mut f: F) where pub fn for_each_lib_search_path<F>(&self, mut f: F) where
F: FnMut(&Path, PathKind) F: FnMut(&SearchPath)
{ {
let mut visited_dirs = FxHashSet::default(); let mut visited_dirs = FxHashSet::default();
visited_dirs.reserve(self.search_paths.paths.len() + 1); visited_dirs.reserve(self.search_paths.len() + 1);
for (path, kind) in self.search_paths.iter(self.kind) { let iter = self.search_paths.iter().filter(|sp| sp.kind.matches(self.kind));
f(path, kind); for search_path in iter {
visited_dirs.insert(path.to_path_buf()); f(search_path);
visited_dirs.insert(search_path.dir.to_path_buf());
} }
debug!("filesearch: searching lib path"); debug!("filesearch: searching lib path");
let tlib_path = make_target_lib_path(self.sysroot, let tlib_path = make_target_lib_path(self.sysroot,
self.triple); self.triple);
if !visited_dirs.contains(&tlib_path) { if !visited_dirs.contains(&tlib_path) {
f(&tlib_path, PathKind::All); f(&SearchPath { kind: PathKind::All, dir: tlib_path });
} }
} }
@@ -62,9 +63,9 @@ impl<'a> FileSearch<'a> {
pub fn search<F>(&self, mut pick: F) pub fn search<F>(&self, mut pick: F)
where F: FnMut(&Path, PathKind) -> FileMatch where F: FnMut(&Path, PathKind) -> FileMatch
{ {
self.for_each_lib_search_path(|lib_search_path, kind| { self.for_each_lib_search_path(|search_path| {
debug!("searching {}", lib_search_path.display()); debug!("searching {}", search_path.dir.display());
let files = match fs::read_dir(lib_search_path) { let files = match fs::read_dir(&search_path.dir) {
Ok(files) => files, Ok(files) => files,
Err(..) => return, Err(..) => return,
}; };
@@ -81,7 +82,7 @@ impl<'a> FileSearch<'a> {
let files2 = files.iter().filter(|p| !is_rlib(p)); let files2 = files.iter().filter(|p| !is_rlib(p));
for path in files1.chain(files2) { for path in files1.chain(files2) {
debug!("testing {}", path.display()); debug!("testing {}", path.display());
let maybe_picked = pick(path, kind); let maybe_picked = pick(path, search_path.kind);
match maybe_picked { match maybe_picked {
FileMatches => { FileMatches => {
debug!("picked {}", path.display()); debug!("picked {}", path.display());
@@ -96,7 +97,7 @@ impl<'a> FileSearch<'a> {
pub fn new(sysroot: &'a Path, pub fn new(sysroot: &'a Path,
triple: &'a str, triple: &'a str,
search_paths: &'a SearchPaths, search_paths: &'a Vec<SearchPath>,
kind: PathKind) -> FileSearch<'a> { kind: PathKind) -> FileSearch<'a> {
debug!("using sysroot = {}, triple = {}", sysroot.display(), triple); debug!("using sysroot = {}, triple = {}", sysroot.display(), triple);
FileSearch { FileSearch {
@@ -110,8 +111,8 @@ impl<'a> FileSearch<'a> {
// Returns a list of directories where target-specific dylibs might be located. // Returns a list of directories where target-specific dylibs might be located.
pub fn get_dylib_search_paths(&self) -> Vec<PathBuf> { pub fn get_dylib_search_paths(&self) -> Vec<PathBuf> {
let mut paths = Vec::new(); let mut paths = Vec::new();
self.for_each_lib_search_path(|lib_search_path, _| { self.for_each_lib_search_path(|search_path| {
paths.push(lib_search_path.to_path_buf()); paths.push(search_path.dir.to_path_buf());
}); });
paths paths
} }
@@ -136,7 +137,7 @@ pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> PathBuf
p p
} }
fn make_target_lib_path(sysroot: &Path, pub fn make_target_lib_path(sysroot: &Path,
target_triple: &str) -> PathBuf { target_triple: &str) -> PathBuf {
sysroot.join(&relative_target_lib_path(sysroot, target_triple)) sysroot.join(&relative_target_lib_path(sysroot, target_triple))
} }

View File

@@ -8,18 +8,14 @@
// option. This file may not be copied, modified, or distributed // option. This file may not be copied, modified, or distributed
// except according to those terms. // except according to those terms.
use std::slice;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use session::{early_error, config}; use session::{early_error, config};
use session::filesearch::make_target_lib_path;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct SearchPaths { pub struct SearchPath {
crate paths: Vec<(PathKind, PathBuf)>, pub kind: PathKind,
} pub dir: PathBuf,
pub struct Iter<'a> {
kind: PathKind,
iter: slice::Iter<'a, (PathKind, PathBuf)>,
} }
#[derive(Eq, PartialEq, Clone, Copy, Debug, PartialOrd, Ord, Hash)] #[derive(Eq, PartialEq, Clone, Copy, Debug, PartialOrd, Ord, Hash)]
@@ -32,12 +28,17 @@ pub enum PathKind {
All, All,
} }
impl SearchPaths { impl PathKind {
pub fn new() -> SearchPaths { pub fn matches(&self, kind: PathKind) -> bool {
SearchPaths { paths: Vec::new() } match (self, kind) {
(PathKind::All, _) | (_, PathKind::All) => true,
_ => *self == kind,
}
} }
}
pub fn add_path(&mut self, path: &str, output: config::ErrorOutputType) { impl SearchPath {
pub fn from_cli_opt(path: &str, output: config::ErrorOutputType) -> Self {
let (kind, path) = if path.starts_with("native=") { let (kind, path) = if path.starts_with("native=") {
(PathKind::Native, &path["native=".len()..]) (PathKind::Native, &path["native=".len()..])
} else if path.starts_with("crate=") { } else if path.starts_with("crate=") {
@@ -54,34 +55,17 @@ impl SearchPaths {
if path.is_empty() { if path.is_empty() {
early_error(output, "empty search path given via `-L`"); early_error(output, "empty search path given via `-L`");
} }
self.paths.push((kind, PathBuf::from(path)));
let dir = PathBuf::from(path);
Self::new(kind, dir)
} }
pub fn iter(&self, kind: PathKind) -> Iter<'_> { pub fn from_sysroot_and_triple(sysroot: &Path, triple: &str) -> Self {
Iter { kind: kind, iter: self.paths.iter() } Self::new(PathKind::All, make_target_lib_path(sysroot, triple))
}
fn new(kind: PathKind, dir: PathBuf) -> Self {
SearchPath { kind, dir }
} }
} }
impl<'a> Iterator for Iter<'a> {
type Item = (&'a Path, PathKind);
fn next(&mut self) -> Option<(&'a Path, PathKind)> {
loop {
match *self.iter.next()? {
(kind, ref p) if self.kind == PathKind::All ||
kind == PathKind::All ||
kind == self.kind => {
return Some((p, kind))
}
_ => {}
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
// This iterator will never return more elements than the base iterator;
// but it can ignore all the remaining elements.
let (_, upper) = self.iter.size_hint();
(0, upper)
}
}

View File

@@ -213,8 +213,8 @@ fn link_binary_output(sess: &Session,
fn archive_search_paths(sess: &Session) -> Vec<PathBuf> { fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
let mut search = Vec::new(); let mut search = Vec::new();
sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path, _| { sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|search_path| {
search.push(path.to_path_buf()); search.push(search_path.dir.to_path_buf());
}); });
search search
@@ -1067,10 +1067,10 @@ fn link_args(cmd: &mut dyn Linker,
fn add_local_native_libraries(cmd: &mut dyn Linker, fn add_local_native_libraries(cmd: &mut dyn Linker,
sess: &Session, sess: &Session,
codegen_results: &CodegenResults) { codegen_results: &CodegenResults) {
sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path, k| { sess.target_filesearch(PathKind::All).for_each_lib_search_path(|search_path| {
match k { match search_path.kind {
PathKind::Framework => { cmd.framework_path(path); } PathKind::Framework => { cmd.framework_path(&search_path.dir); }
_ => { cmd.include_path(&fix_windows_verbatim_for_gcc(path)); } _ => { cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir)); }
} }
}); });

View File

@@ -20,7 +20,7 @@ use rustc::session::early_error;
use rustc::session::config::{CodegenOptions, DebuggingOptions, ErrorOutputType, Externs}; use rustc::session::config::{CodegenOptions, DebuggingOptions, ErrorOutputType, Externs};
use rustc::session::config::{nightly_options, build_codegen_options, build_debugging_options, use rustc::session::config::{nightly_options, build_codegen_options, build_debugging_options,
get_cmd_lint_options}; get_cmd_lint_options};
use rustc::session::search_paths::SearchPaths; use rustc::session::search_paths::SearchPath;
use rustc_driver; use rustc_driver;
use rustc_target::spec::TargetTriple; use rustc_target::spec::TargetTriple;
use syntax::edition::Edition; use syntax::edition::Edition;
@@ -46,7 +46,7 @@ pub struct Options {
/// How to format errors and warnings. /// How to format errors and warnings.
pub error_format: ErrorOutputType, pub error_format: ErrorOutputType,
/// Library search paths to hand to the compiler. /// Library search paths to hand to the compiler.
pub libs: SearchPaths, pub libs: Vec<SearchPath>,
/// The list of external crates to link against. /// The list of external crates to link against.
pub externs: Externs, pub externs: Externs,
/// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`. /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
@@ -295,10 +295,9 @@ impl Options {
} }
let input = PathBuf::from(&matches.free[0]); let input = PathBuf::from(&matches.free[0]);
let mut libs = SearchPaths::new(); let libs = matches.opt_strs("L").iter()
for s in &matches.opt_strs("L") { .map(|s| SearchPath::from_cli_opt(s, error_format))
libs.add_path(s, error_format); .collect();
}
let externs = match parse_externs(&matches) { let externs = match parse_externs(&matches) {
Ok(ex) => ex, Ok(ex) => ex,
Err(err) => { Err(err) => {

View File

@@ -51,7 +51,7 @@ use html::render::RenderInfo;
use passes; use passes;
pub use rustc::session::config::{Input, Options, CodegenOptions}; pub use rustc::session::config::{Input, Options, CodegenOptions};
pub use rustc::session::search_paths::SearchPaths; pub use rustc::session::search_paths::SearchPath;
pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>; pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;

View File

@@ -21,7 +21,7 @@ use rustc::hir;
use rustc::hir::intravisit; use rustc::hir::intravisit;
use rustc::session::{self, CompileIncomplete, config}; use rustc::session::{self, CompileIncomplete, config};
use rustc::session::config::{OutputType, OutputTypes, Externs, CodegenOptions}; use rustc::session::config::{OutputType, OutputTypes, Externs, CodegenOptions};
use rustc::session::search_paths::{SearchPaths, PathKind}; use rustc::session::search_paths::{SearchPath, PathKind};
use syntax::ast; use syntax::ast;
use syntax::source_map::SourceMap; use syntax::source_map::SourceMap;
use syntax::edition::Edition; use syntax::edition::Edition;
@@ -187,7 +187,7 @@ fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
} }
fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize, fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize,
cfgs: Vec<String>, libs: SearchPaths, cfgs: Vec<String>, libs: Vec<SearchPath>,
cg: CodegenOptions, externs: Externs, cg: CodegenOptions, externs: Externs,
should_panic: bool, no_run: bool, as_test_harness: bool, should_panic: bool, no_run: bool, as_test_harness: bool,
compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions, compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions,
@@ -556,7 +556,7 @@ pub struct Collector {
names: Vec<String>, names: Vec<String>,
cfgs: Vec<String>, cfgs: Vec<String>,
libs: SearchPaths, libs: Vec<SearchPath>,
cg: CodegenOptions, cg: CodegenOptions,
externs: Externs, externs: Externs,
use_headers: bool, use_headers: bool,
@@ -571,7 +571,7 @@ pub struct Collector {
} }
impl Collector { impl Collector {
pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, cg: CodegenOptions, pub fn new(cratename: String, cfgs: Vec<String>, libs: Vec<SearchPath>, cg: CodegenOptions,
externs: Externs, use_headers: bool, opts: TestOptions, externs: Externs, use_headers: bool, opts: TestOptions,
maybe_sysroot: Option<PathBuf>, source_map: Option<Lrc<SourceMap>>, maybe_sysroot: Option<PathBuf>, source_map: Option<Lrc<SourceMap>>,
filename: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition) -> Collector { filename: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition) -> Collector {