Skip to main content

rucc_session/
fs.rs

1//! The file system the compiler reads through, and the include search path.
2//!
3//! Design: `spec/04-driver-and-cli.md` section 4.4 for the search order, and
4//! `spec/05-preprocessor.md` section 5.4 for what `#include_next` means.
5//!
6//! Nothing below the driver calls `std::fs`. That is what makes the compiler usable as a
7//! library, and it is what makes a preprocessor test a value rather than a temporary
8//! directory: [`MemoryFileSystem`] is a map from path to bytes, and a test that needs a
9//! twelve deep header nest builds one in twelve lines with no clean up to forget.
10//!
11//! ```
12//! use rucc_session::{FileSystem, IncludeForm, MemoryFileSystem, SearchPath};
13//!
14//! let mut fs = MemoryFileSystem::new();
15//! fs.insert("/usr/include/stdio.h", *b"int puts(const char *);\n");
16//!
17//! let mut search = SearchPath::new();
18//! search.push_system("/usr/include");
19//!
20//! let found = search.resolve(&fs, "stdio.h", IncludeForm::Angled, None, 0).unwrap();
21//! assert_eq!(found.name.replace('\\', "/"), "/usr/include/stdio.h");
22//! assert!(found.is_system);
23//! ```
24
25use std::collections::BTreeMap;
26use std::fmt;
27use std::io;
28use std::path::{Path, PathBuf};
29
30use rucc_diag::SourceBytes;
31
32use crate::runtime;
33
34/// Where the compiler reads source from.
35///
36/// The one method is deliberate. Everything the preprocessor wants to know about a file, up
37/// to and including whether it exists, is answered by trying to read it, and an interface
38/// with a separate `exists` invites the race where the answer changes between the two calls.
39pub trait FileSystem: fmt::Debug + Send + Sync {
40    /// Reads a file.
41    ///
42    /// # Errors
43    ///
44    /// Whatever the underlying file system says. [`io::ErrorKind::NotFound`] is the ordinary
45    /// case during an include search and is not by itself a problem.
46    fn read(&self, path: &Path) -> io::Result<SourceBytes>;
47}
48
49/// A file system held in memory, for tests and for embedding the compiler.
50#[derive(Debug, Default)]
51pub struct MemoryFileSystem {
52    files: BTreeMap<PathBuf, SourceBytes>,
53}
54
55impl MemoryFileSystem {
56    /// An empty file system.
57    pub fn new() -> MemoryFileSystem {
58        MemoryFileSystem::default()
59    }
60
61    /// Adds a file, replacing any file already at that path.
62    pub fn insert(
63        &mut self,
64        path: impl Into<PathBuf>,
65        contents: impl AsRef<[u8]> + Send + Sync + 'static,
66    ) {
67        self.files.insert(path.into(), SourceBytes::new(contents));
68    }
69
70    /// How many files it holds.
71    pub fn len(&self) -> usize {
72        self.files.len()
73    }
74
75    /// Whether it holds nothing.
76    pub fn is_empty(&self) -> bool {
77        self.files.is_empty()
78    }
79}
80
81impl FileSystem for MemoryFileSystem {
82    fn read(&self, path: &Path) -> io::Result<SourceBytes> {
83        self.files
84            .get(path)
85            .cloned()
86            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no such file"))
87    }
88}
89
90/// Which spelling an `#include` used.
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
92pub enum IncludeForm {
93    /// `#include "local.h"`, which looks next to the including file first.
94    Quoted,
95    /// `#include <stdio.h>`, which does not.
96    Angled,
97}
98
99/// One directory on the search path.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct Dir {
102    /// The directory, as the user spelled it. Not canonicalised, because a diagnostic that
103    /// says `../include/foo.h` is more use than one naming a path the user never typed.
104    pub path: PathBuf,
105    /// Whether headers found here are system headers, which suppresses warnings in them and
106    /// sets the `3` flag on a `-E` line marker.
107    pub is_system: bool,
108}
109
110/// A header that was found.
111#[derive(Debug, Clone)]
112pub struct Found {
113    /// The path to open, which is the directory joined with the name as written.
114    pub path: PathBuf,
115    /// That path as a string, for the source map and for diagnostics.
116    pub name: String,
117    /// Whether it came from a system directory.
118    pub is_system: bool,
119    /// Where an `#include_next` written in this file should start looking.
120    ///
121    /// One past the entry this header came from, or zero for a header found next to the file
122    /// that included it, because that directory is not on the path and there is nothing to
123    /// continue past. Carrying the answer rather than the position is what keeps the two
124    /// cases from being confused at the call site.
125    pub next: usize,
126    /// The contents.
127    pub bytes: SourceBytes,
128}
129
130/// The directories a header is looked for in, in order.
131///
132/// GCC's order, because a different one produces header shadowing bugs that are miserable to
133/// diagnose: `-iquote` first and only for a quoted include, then `-I`, then `-isystem`, then
134/// the configured system directories, then `-idirafter`. The directory of the including file
135/// comes before all of it for a quoted include, and it is not part of the numbered list
136/// because `#include_next` must not be able to land back on it.
137#[derive(Debug, Default, Clone, PartialEq, Eq)]
138pub struct SearchPath {
139    dirs: Vec<Dir>,
140    /// Where the `-I` directories begin, which is where an angled include starts looking.
141    quote_end: usize,
142    /// Where the `-isystem` and configured system directories begin.
143    bracket_end: usize,
144    /// Where the `-idirafter` directories begin.
145    system_end: usize,
146}
147
148impl SearchPath {
149    /// An empty search path.
150    pub fn new() -> SearchPath {
151        SearchPath::default()
152    }
153
154    /// Adds a `-iquote` directory, searched only for a quoted include.
155    pub fn push_quote(&mut self, dir: impl Into<PathBuf>) {
156        let at = self.quote_end;
157        self.insert(at, dir.into(), false);
158        self.quote_end += 1;
159        self.bracket_end += 1;
160        self.system_end += 1;
161    }
162
163    /// Adds a `-I` directory.
164    pub fn push_bracket(&mut self, dir: impl Into<PathBuf>) {
165        let at = self.bracket_end;
166        self.insert(at, dir.into(), false);
167        self.bracket_end += 1;
168        self.system_end += 1;
169    }
170
171    /// Adds a `-isystem` directory, or one of the target's configured system directories.
172    pub fn push_system(&mut self, dir: impl Into<PathBuf>) {
173        let at = self.system_end;
174        self.insert(at, dir.into(), true);
175        self.system_end += 1;
176    }
177
178    /// Adds a `-idirafter` directory, which is searched after everything else.
179    pub fn push_after(&mut self, dir: impl Into<PathBuf>) {
180        let at = self.dirs.len();
181        self.insert(at, dir.into(), true);
182    }
183
184    fn insert(&mut self, at: usize, path: PathBuf, is_system: bool) {
185        self.dirs.insert(at, Dir { path, is_system });
186    }
187
188    /// Every directory, in search order.
189    pub fn dirs(&self) -> &[Dir] {
190        &self.dirs
191    }
192
193    /// The first entry an include of this form looks at.
194    ///
195    /// An angled include skips the `-iquote` directories, which is the only difference
196    /// between the two chains once the including file's own directory is out of the way.
197    pub fn start(&self, form: IncludeForm) -> usize {
198        match form {
199            IncludeForm::Quoted => 0,
200            IncludeForm::Angled => self.quote_end,
201        }
202    }
203
204    /// Finds `name`, starting at entry `from` of the search path.
205    ///
206    /// `relative_to` is the directory of the file doing the including, tried first for a
207    /// quoted include and ignored otherwise. Pass `None` for an `#include_next`, which is
208    /// defined as continuing past the directory the current file was found in and so must not
209    /// look next to it again.
210    ///
211    /// An absolute name is opened directly and the search path is not consulted, which is
212    /// what every C compiler does and what a generated header with an absolute path needs.
213    pub fn resolve(
214        &self,
215        fs: &dyn FileSystem,
216        name: &str,
217        form: IncludeForm,
218        relative_to: Option<&Path>,
219        from: usize,
220    ) -> Option<Found> {
221        let as_path = Path::new(name);
222        if is_absolute(as_path) {
223            let bytes = open(fs, as_path).ok()?;
224            return Some(Found {
225                path: as_path.to_path_buf(),
226                name: name.to_owned(),
227                is_system: false,
228                next: 0,
229                bytes,
230            });
231        }
232        if form == IncludeForm::Quoted {
233            if let Some(dir) = relative_to {
234                let path = dir.join(as_path);
235                if let Ok(bytes) = open(fs, &path) {
236                    return Some(Found {
237                        name: display(&path),
238                        path,
239                        is_system: false,
240                        // The including file's own directory is not an entry on the path, so
241                        // an `#include_next` from a header found there starts at the top of
242                        // the path rather than one past a position that does not exist.
243                        next: 0,
244                        bytes,
245                    });
246                }
247            }
248        }
249        for (at, dir) in self.dirs.iter().enumerate().skip(from) {
250            let path = dir.path.join(as_path);
251            if let Ok(bytes) = open(fs, &path) {
252                return Some(Found {
253                    name: display(&path),
254                    path,
255                    is_system: dir.is_system,
256                    next: at + 1,
257                    bytes,
258                });
259            }
260        }
261        None
262    }
263
264    /// The directories a failed [`SearchPath::resolve`] with the same arguments looked in.
265    ///
266    /// `spec/05-preprocessor.md` section 5.7 makes printing this the required behaviour for a
267    /// failed include, because "file not found" without the list of places that were tried is
268    /// the diagnostic that wastes the most time in this part of the compiler.
269    pub fn tried(
270        &self,
271        name: &str,
272        form: IncludeForm,
273        relative_to: Option<&Path>,
274        from: usize,
275    ) -> Vec<PathBuf> {
276        if is_absolute(Path::new(name)) {
277            return Vec::new();
278        }
279        let mut list = Vec::new();
280        if form == IncludeForm::Quoted {
281            if let Some(dir) = relative_to {
282                list.push(dir.to_path_buf());
283            }
284        }
285        list.extend(self.dirs.iter().skip(from).map(|d| d.path.clone()));
286        list
287    }
288}
289
290/// Reads a path the search produced, from the shipped headers first and the disk after.
291///
292/// This is the one place the compiler's own headers are handed out, and it is here rather
293/// than in a [`FileSystem`] implementation on purpose. They are not files, they belong to
294/// every implementation of the trait equally, and the only way to reach them is through a
295/// search path entry spelled [`runtime::DIR`], which no real directory can be spelled as.
296fn open(fs: &dyn FileSystem, path: &Path) -> io::Result<SourceBytes> {
297    match runtime::read(path) {
298        Some(bytes) => Ok(bytes),
299        None => fs.read(path),
300    }
301}
302
303/// A path as a string, lossily, because a diagnostic has to say something.
304fn display(path: &Path) -> String {
305    path.to_string_lossy().into_owned()
306}
307
308/// Whether an include name names a file outright rather than one to be searched for.
309///
310/// `Path::is_absolute` is false for `/usr/include/stdio.h` on Windows, because it has no
311/// drive letter. A C file that says `#include "/usr/include/stdio.h"` means a path from the
312/// root whatever host is compiling it, so a leading separator counts here as well.
313fn is_absolute(path: &Path) -> bool {
314    path.is_absolute() || path.has_root()
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    fn fs_with(files: &[&str]) -> MemoryFileSystem {
322        let mut fs = MemoryFileSystem::new();
323        for f in files {
324            fs.insert(*f, format!("/* {f} */\n").into_bytes());
325        }
326        fs
327    }
328
329    fn text(found: &Found) -> String {
330        String::from_utf8_lossy(found.bytes.as_slice()).into_owned()
331    }
332
333    /// A path with forward slashes, because `Path::join` uses a backslash on Windows and
334    /// these tests are about the search order rather than about separators.
335    fn norm(path: &str) -> String {
336        path.replace('\\', "/")
337    }
338
339    #[test]
340    fn a_missing_file_is_not_found_rather_than_an_error() {
341        let fs = MemoryFileSystem::new();
342        let kind = fs.read(Path::new("/nope.h")).err().map(|e| e.kind());
343        assert_eq!(kind, Some(io::ErrorKind::NotFound));
344        assert!(fs.is_empty());
345    }
346
347    #[test]
348    fn quote_directories_are_invisible_to_an_angled_include() {
349        let fs = fs_with(&["/q/a.h", "/i/a.h"]);
350        let mut search = SearchPath::new();
351        search.push_quote("/q");
352        search.push_bracket("/i");
353
354        let quoted = search.resolve(&fs, "a.h", IncludeForm::Quoted, None, 0).unwrap();
355        assert_eq!(norm(&quoted.name), "/q/a.h");
356        let angled = search
357            .resolve(&fs, "a.h", IncludeForm::Angled, None, search.start(IncludeForm::Angled))
358            .unwrap();
359        assert_eq!(norm(&angled.name), "/i/a.h");
360    }
361
362    #[test]
363    fn the_including_files_own_directory_comes_first_for_a_quoted_include() {
364        let fs = fs_with(&["/src/a.h", "/i/a.h"]);
365        let mut search = SearchPath::new();
366        search.push_bracket("/i");
367        let here = Path::new("/src");
368
369        let quoted = search.resolve(&fs, "a.h", IncludeForm::Quoted, Some(here), 0).unwrap();
370        assert_eq!(norm(&quoted.name), "/src/a.h");
371        // An angled include does not look there, even though it was passed.
372        let angled = search.resolve(&fs, "a.h", IncludeForm::Angled, Some(here), 0).unwrap();
373        assert_eq!(norm(&angled.name), "/i/a.h");
374    }
375
376    #[test]
377    fn the_order_is_iquote_then_i_then_isystem_then_idirafter() {
378        let fs = fs_with(&["/after/a.h", "/sys/a.h", "/i/a.h", "/q/a.h"]);
379        let mut search = SearchPath::new();
380        // Pushed in an order that is not the search order, because a driver reads the command
381        // line left to right and the groups interleave.
382        search.push_after("/after");
383        search.push_system("/sys");
384        search.push_bracket("/i");
385        search.push_quote("/q");
386        let order: Vec<_> = search.dirs().iter().map(|d| norm(&d.path.to_string_lossy())).collect();
387        assert_eq!(order, ["/q", "/i", "/sys", "/after"]);
388
389        let found = search.resolve(&fs, "a.h", IncludeForm::Quoted, None, 0).unwrap();
390        assert_eq!(norm(&found.name), "/q/a.h");
391        assert_eq!(found.next, 1);
392    }
393
394    #[test]
395    fn a_system_directory_marks_what_it_holds_as_a_system_header() {
396        let fs = fs_with(&["/i/a.h", "/sys/b.h", "/after/c.h"]);
397        let mut search = SearchPath::new();
398        search.push_bracket("/i");
399        search.push_system("/sys");
400        search.push_after("/after");
401        let get = |n| search.resolve(&fs, n, IncludeForm::Angled, None, 0).unwrap();
402        assert!(!get("a.h").is_system);
403        assert!(get("b.h").is_system);
404        assert!(get("c.h").is_system);
405    }
406
407    #[test]
408    fn include_next_continues_past_the_directory_the_current_file_came_from() {
409        let fs = fs_with(&["/a/limits.h", "/b/limits.h", "/c/limits.h"]);
410        let mut search = SearchPath::new();
411        search.push_bracket("/a");
412        search.push_bracket("/b");
413        search.push_bracket("/c");
414
415        let first = search.resolve(&fs, "limits.h", IncludeForm::Angled, None, 0).unwrap();
416        assert_eq!(norm(&first.name), "/a/limits.h");
417        let second =
418            search.resolve(&fs, "limits.h", IncludeForm::Angled, None, first.next).unwrap();
419        assert_eq!(norm(&second.name), "/b/limits.h");
420        let third =
421            search.resolve(&fs, "limits.h", IncludeForm::Angled, None, second.next).unwrap();
422        assert_eq!(norm(&third.name), "/c/limits.h");
423        assert!(search.resolve(&fs, "limits.h", IncludeForm::Angled, None, third.next).is_none());
424    }
425
426    #[test]
427    fn a_name_with_a_directory_in_it_is_joined_onto_each_entry() {
428        let fs = fs_with(&["/i/sys/types.h"]);
429        let mut search = SearchPath::new();
430        search.push_bracket("/i");
431        let found = search.resolve(&fs, "sys/types.h", IncludeForm::Angled, None, 0).unwrap();
432        assert_eq!(norm(&found.name), "/i/sys/types.h");
433        assert_eq!(text(&found), "/* /i/sys/types.h */\n");
434    }
435
436    #[test]
437    fn an_absolute_name_ignores_the_search_path() {
438        let fs = fs_with(&["/gen/config.h", "/i/gen/config.h"]);
439        let mut search = SearchPath::new();
440        search.push_bracket("/i");
441        let found = search.resolve(&fs, "/gen/config.h", IncludeForm::Angled, None, 0).unwrap();
442        assert_eq!(norm(&found.name), "/gen/config.h");
443        assert!(search.tried("/gen/config.h", IncludeForm::Angled, None, 0).is_empty());
444    }
445
446    #[test]
447    fn the_list_of_places_tried_is_the_list_that_was_searched() {
448        let fs = MemoryFileSystem::new();
449        let mut search = SearchPath::new();
450        search.push_quote("/q");
451        search.push_bracket("/i");
452        search.push_system("/sys");
453        let here = Path::new("/src");
454
455        assert!(search.resolve(&fs, "a.h", IncludeForm::Quoted, Some(here), 0).is_none());
456        let tried = search.tried("a.h", IncludeForm::Quoted, Some(here), 0);
457        let tried: Vec<_> = tried.iter().map(|p| norm(&p.to_string_lossy())).collect();
458        assert_eq!(tried, ["/src", "/q", "/i", "/sys"]);
459
460        let start = search.start(IncludeForm::Angled);
461        let tried = search.tried("a.h", IncludeForm::Angled, Some(here), start);
462        let tried: Vec<_> = tried.iter().map(|p| norm(&p.to_string_lossy())).collect();
463        assert_eq!(tried, ["/i", "/sys"]);
464    }
465
466    #[test]
467    fn a_header_found_next_to_its_includer_does_not_skip_the_whole_path_afterwards() {
468        // `at` for a file found beside its includer has to leave `at + 1` at the top of the
469        // path, because the directory it was found in is not on the path at all.
470        let fs = fs_with(&["/src/a.h", "/i/b.h"]);
471        let mut search = SearchPath::new();
472        search.push_bracket("/i");
473        let found =
474            search.resolve(&fs, "a.h", IncludeForm::Quoted, Some(Path::new("/src")), 0).unwrap();
475        assert_eq!(found.next, 0);
476        let next = search.resolve(&fs, "b.h", IncludeForm::Angled, None, found.next).unwrap();
477        assert_eq!(norm(&next.name), "/i/b.h");
478    }
479}