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