rustc_session/
search_paths.rs

1use std::path::{Path, PathBuf};
2use std::sync::Arc;
3
4use rustc_macros::{Decodable, Encodable, HashStable_Generic};
5use rustc_target::spec::TargetTuple;
6
7use crate::EarlyDiagCtxt;
8use crate::filesearch::make_target_lib_path;
9
10#[derive(Clone, Debug)]
11pub struct SearchPath {
12    pub kind: PathKind,
13    pub dir: PathBuf,
14    pub files: FilesIndex,
15}
16
17/// [FilesIndex] contains paths that can be efficiently looked up with (prefix, suffix) pairs.
18#[derive(Clone, Debug)]
19pub struct FilesIndex(Vec<(Arc<str>, SearchPathFile)>);
20
21impl FilesIndex {
22    /// Look up [SearchPathFile] by (prefix, suffix) pair.
23    pub fn query<'s>(
24        &'s self,
25        prefix: &str,
26        suffix: &str,
27    ) -> Option<impl Iterator<Item = (String, &'s SearchPathFile)>> {
28        let start = self.0.partition_point(|(k, _)| **k < *prefix);
29        if start == self.0.len() {
30            return None;
31        }
32        let end = self.0[start..].partition_point(|(k, _)| k.starts_with(prefix));
33        let prefixed_items = &self.0[start..][..end];
34
35        let ret = prefixed_items.into_iter().filter_map(move |(k, v)| {
36            k.ends_with(suffix).then(|| {
37                (
38                    String::from(
39                        &v.file_name_str[prefix.len()..v.file_name_str.len() - suffix.len()],
40                    ),
41                    v,
42                )
43            })
44        });
45        Some(ret)
46    }
47    pub fn retain(&mut self, prefixes: &[&str]) {
48        self.0.retain(|(k, _)| prefixes.iter().any(|prefix| k.starts_with(prefix)));
49    }
50}
51/// The obvious implementation of `SearchPath::files` is a `Vec<PathBuf>`. But
52/// it is searched repeatedly by `find_library_crate`, and the searches involve
53/// checking the prefix and suffix of the filename of each `PathBuf`. This is
54/// doable, but very slow, because it involves calls to `file_name` and
55/// `extension` that are themselves slow.
56///
57/// This type augments the `PathBuf` with an `String` containing the
58/// `PathBuf`'s filename. The prefix and suffix checking is much faster on the
59/// `String` than the `PathBuf`. (The filename must be valid UTF-8. If it's
60/// not, the entry should be skipped, because all Rust output files are valid
61/// UTF-8, and so a non-UTF-8 filename couldn't be one we're looking for.)
62#[derive(Clone, Debug)]
63pub struct SearchPathFile {
64    pub path: Arc<Path>,
65    pub file_name_str: Arc<str>,
66}
67
68#[derive(PartialEq, Clone, Copy, Debug, Hash, Eq, Encodable, Decodable, HashStable_Generic)]
69pub enum PathKind {
70    Native,
71    Crate,
72    Dependency,
73    Framework,
74    ExternFlag,
75    All,
76}
77
78impl PathKind {
79    pub fn matches(&self, kind: PathKind) -> bool {
80        match (self, kind) {
81            (PathKind::All, _) | (_, PathKind::All) => true,
82            _ => *self == kind,
83        }
84    }
85}
86
87impl SearchPath {
88    pub fn from_cli_opt(
89        sysroot: &Path,
90        triple: &TargetTuple,
91        early_dcx: &EarlyDiagCtxt,
92        path: &str,
93        is_unstable_enabled: bool,
94    ) -> Self {
95        let (kind, path) = if let Some(stripped) = path.strip_prefix("native=") {
96            (PathKind::Native, stripped)
97        } else if let Some(stripped) = path.strip_prefix("crate=") {
98            (PathKind::Crate, stripped)
99        } else if let Some(stripped) = path.strip_prefix("dependency=") {
100            (PathKind::Dependency, stripped)
101        } else if let Some(stripped) = path.strip_prefix("framework=") {
102            (PathKind::Framework, stripped)
103        } else if let Some(stripped) = path.strip_prefix("all=") {
104            (PathKind::All, stripped)
105        } else {
106            (PathKind::All, path)
107        };
108        let dir = match path.strip_prefix("@RUSTC_BUILTIN") {
109            Some(stripped) => {
110                if !is_unstable_enabled {
111                    #[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
112                    early_dcx.early_fatal(
113                        "the `-Z unstable-options` flag must also be passed to \
114                         enable the use of `@RUSTC_BUILTIN`",
115                    );
116                }
117
118                make_target_lib_path(sysroot, triple.tuple()).join("builtin").join(stripped)
119            }
120            None => PathBuf::from(path),
121        };
122        if dir.as_os_str().is_empty() {
123            #[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
124            early_dcx.early_fatal("empty search path given via `-L`");
125        }
126
127        Self::new(kind, dir)
128    }
129
130    pub fn from_sysroot_and_triple(sysroot: &Path, triple: &str) -> Self {
131        Self::new(PathKind::All, make_target_lib_path(sysroot, triple))
132    }
133
134    pub fn new(kind: PathKind, dir: PathBuf) -> Self {
135        // Get the files within the directory.
136        let mut files = match std::fs::read_dir(&dir) {
137            Ok(files) => files
138                .filter_map(|e| {
139                    e.ok().and_then(|e| {
140                        e.file_name().to_str().map(|s| {
141                            let file_name_str: Arc<str> = s.into();
142                            (
143                                Arc::clone(&file_name_str),
144                                SearchPathFile { path: e.path().into(), file_name_str },
145                            )
146                        })
147                    })
148                })
149                .collect::<Vec<_>>(),
150
151            Err(..) => Default::default(),
152        };
153        files.sort_by(|(lhs, _), (rhs, _)| lhs.cmp(rhs));
154        let files = FilesIndex(files);
155        SearchPath { kind, dir, files }
156    }
157}