]> git.lizzy.rs Git - rust.git/blob - src/librustc/metadata/filesearch.rs
Replace all ~"" with "".to_owned()
[rust.git] / src / librustc / metadata / filesearch.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![allow(non_camel_case_types)]
12
13 use std::cell::RefCell;
14 use std::os;
15 use std::io::fs;
16 use collections::HashSet;
17
18 use myfs = util::fs;
19
20 pub enum FileMatch { FileMatches, FileDoesntMatch }
21
22 // A module for searching for libraries
23 // FIXME (#2658): I'm not happy how this module turned out. Should
24 // probably just be folded into cstore.
25
26 /// Functions with type `pick` take a parent directory as well as
27 /// a file found in that directory.
28 pub type pick<'a> = |path: &Path|: 'a -> FileMatch;
29
30 pub struct FileSearch<'a> {
31     pub sysroot: &'a Path,
32     pub addl_lib_search_paths: &'a RefCell<HashSet<Path>>,
33     pub target_triple: &'a str
34 }
35
36 impl<'a> FileSearch<'a> {
37     pub fn for_each_lib_search_path(&self, f: |&Path| -> FileMatch) {
38         let mut visited_dirs = HashSet::new();
39         let mut found = false;
40
41         debug!("filesearch: searching additional lib search paths [{:?}]",
42                self.addl_lib_search_paths.borrow().len());
43         for path in self.addl_lib_search_paths.borrow().iter() {
44             match f(path) {
45                 FileMatches => found = true,
46                 FileDoesntMatch => ()
47             }
48             visited_dirs.insert(path.as_vec().to_owned());
49         }
50
51         debug!("filesearch: searching target lib path");
52         let tlib_path = make_target_lib_path(self.sysroot,
53                                     self.target_triple);
54         if !visited_dirs.contains_equiv(&tlib_path.as_vec()) {
55             match f(&tlib_path) {
56                 FileMatches => found = true,
57                 FileDoesntMatch => ()
58             }
59         }
60         visited_dirs.insert(tlib_path.as_vec().to_owned());
61         // Try RUST_PATH
62         if !found {
63             let rustpath = rust_path();
64             for path in rustpath.iter() {
65                 let tlib_path = make_rustpkg_target_lib_path(
66                     self.sysroot, path, self.target_triple);
67                 debug!("is {} in visited_dirs? {:?}", tlib_path.display(),
68                         visited_dirs.contains_equiv(&tlib_path.as_vec().to_owned()));
69
70                 if !visited_dirs.contains_equiv(&tlib_path.as_vec()) {
71                     visited_dirs.insert(tlib_path.as_vec().to_owned());
72                     // Don't keep searching the RUST_PATH if one match turns up --
73                     // if we did, we'd get a "multiple matching crates" error
74                     match f(&tlib_path) {
75                        FileMatches => {
76                            break;
77                        }
78                        FileDoesntMatch => ()
79                     }
80                 }
81             }
82         }
83     }
84
85     pub fn get_target_lib_path(&self) -> Path {
86         make_target_lib_path(self.sysroot, self.target_triple)
87     }
88
89     pub fn search(&self, pick: pick) {
90         self.for_each_lib_search_path(|lib_search_path| {
91             debug!("searching {}", lib_search_path.display());
92             match fs::readdir(lib_search_path) {
93                 Ok(files) => {
94                     let mut rslt = FileDoesntMatch;
95                     let is_rlib = |p: & &Path| {
96                         p.extension_str() == Some("rlib")
97                     };
98                     // Reading metadata out of rlibs is faster, and if we find both
99                     // an rlib and a dylib we only read one of the files of
100                     // metadata, so in the name of speed, bring all rlib files to
101                     // the front of the search list.
102                     let files1 = files.iter().filter(|p| is_rlib(p));
103                     let files2 = files.iter().filter(|p| !is_rlib(p));
104                     for path in files1.chain(files2) {
105                         debug!("testing {}", path.display());
106                         let maybe_picked = pick(path);
107                         match maybe_picked {
108                             FileMatches => {
109                                 debug!("picked {}", path.display());
110                                 rslt = FileMatches;
111                             }
112                             FileDoesntMatch => {
113                                 debug!("rejected {}", path.display());
114                             }
115                         }
116                     }
117                     rslt
118                 }
119                 Err(..) => FileDoesntMatch,
120             }
121         });
122     }
123
124     pub fn new(sysroot: &'a Path,
125                target_triple: &'a str,
126                addl_lib_search_paths: &'a RefCell<HashSet<Path>>) -> FileSearch<'a> {
127         debug!("using sysroot = {}", sysroot.display());
128         FileSearch {
129             sysroot: sysroot,
130             addl_lib_search_paths: addl_lib_search_paths,
131             target_triple: target_triple
132         }
133     }
134 }
135
136 pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
137     let mut p = Path::new(find_libdir(sysroot));
138     assert!(p.is_relative());
139     p.push(rustlibdir());
140     p.push(target_triple);
141     p.push("lib");
142     p
143 }
144
145 fn make_target_lib_path(sysroot: &Path,
146                         target_triple: &str) -> Path {
147     sysroot.join(&relative_target_lib_path(sysroot, target_triple))
148 }
149
150 fn make_rustpkg_target_lib_path(sysroot: &Path,
151                                 dir: &Path,
152                                 target_triple: &str) -> Path {
153     let mut p = dir.join(find_libdir(sysroot));
154     p.push(target_triple);
155     p
156 }
157
158 pub fn get_or_default_sysroot() -> Path {
159     // Follow symlinks.  If the resolved path is relative, make it absolute.
160     fn canonicalize(path: Option<Path>) -> Option<Path> {
161         path.and_then(|path|
162             match myfs::realpath(&path) {
163                 Ok(canon) => Some(canon),
164                 Err(e) => fail!("failed to get realpath: {}", e),
165             })
166     }
167
168     match canonicalize(os::self_exe_name()) {
169         Some(mut p) => { p.pop(); p.pop(); p }
170         None => fail!("can't determine value for sysroot")
171     }
172 }
173
174 #[cfg(windows)]
175 static PATH_ENTRY_SEPARATOR: &'static str = ";";
176 #[cfg(not(windows))]
177 static PATH_ENTRY_SEPARATOR: &'static str = ":";
178
179 /// Returns RUST_PATH as a string, without default paths added
180 pub fn get_rust_path() -> Option<~str> {
181     os::getenv("RUST_PATH")
182 }
183
184 /// Returns the value of RUST_PATH, as a list
185 /// of Paths. Includes default entries for, if they exist:
186 /// $HOME/.rust
187 /// DIR/.rust for any DIR that's the current working directory
188 /// or an ancestor of it
189 pub fn rust_path() -> Vec<Path> {
190     let mut env_rust_path: Vec<Path> = match get_rust_path() {
191         Some(env_path) => {
192             let env_path_components =
193                 env_path.split_str(PATH_ENTRY_SEPARATOR);
194             env_path_components.map(|s| Path::new(s)).collect()
195         }
196         None => Vec::new()
197     };
198     let mut cwd = os::getcwd();
199     // now add in default entries
200     let cwd_dot_rust = cwd.join(".rust");
201     if !env_rust_path.contains(&cwd_dot_rust) {
202         env_rust_path.push(cwd_dot_rust);
203     }
204     if !env_rust_path.contains(&cwd) {
205         env_rust_path.push(cwd.clone());
206     }
207     loop {
208         if { let f = cwd.filename(); f.is_none() || f.unwrap() == bytes!("..") } {
209             break
210         }
211         cwd.set_filename(".rust");
212         if !env_rust_path.contains(&cwd) && cwd.exists() {
213             env_rust_path.push(cwd.clone());
214         }
215         cwd.pop();
216     }
217     let h = os::homedir();
218     for h in h.iter() {
219         let p = h.join(".rust");
220         if !env_rust_path.contains(&p) && p.exists() {
221             env_rust_path.push(p);
222         }
223     }
224     env_rust_path
225 }
226
227 // The name of the directory rustc expects libraries to be located.
228 // On Unix should be "lib", on windows "bin"
229 #[cfg(unix)]
230 fn find_libdir(sysroot: &Path) -> ~str {
231     // FIXME: This is a quick hack to make the rustc binary able to locate
232     // Rust libraries in Linux environments where libraries might be installed
233     // to lib64/lib32. This would be more foolproof by basing the sysroot off
234     // of the directory where librustc is located, rather than where the rustc
235     // binary is.
236
237     if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
238         return primary_libdir_name();
239     } else {
240         return secondary_libdir_name();
241     }
242
243     #[cfg(target_word_size = "64")]
244     fn primary_libdir_name() -> ~str { "lib64".to_owned() }
245
246     #[cfg(target_word_size = "32")]
247     fn primary_libdir_name() -> ~str { "lib32".to_owned() }
248
249     fn secondary_libdir_name() -> ~str { "lib".to_owned() }
250 }
251
252 #[cfg(windows)]
253 fn find_libdir(_sysroot: &Path) -> ~str {
254     "bin".to_owned()
255 }
256
257 // The name of rustc's own place to organize libraries.
258 // Used to be "rustc", now the default is "rustlib"
259 pub fn rustlibdir() -> ~str {
260     "rustlib".to_owned()
261 }